今天小编就为大家带来一篇有关php多表查询的文章。小编觉得挺实用的,为此分享给大家做个参考。一起跟随小编过来看看吧。
php如何实现多表查询
多表联查就是要查询的结果是需要获取多个表的内容,把它们的关系建立为一个临时存在的表。
多表联合查询是不可以进行索引优化查询速度的,所以一般情况下不建议使用。
1、使用mysqli_connect连接数据库
<?php
header("Content-Type: text/html;charset=utf-8");
$dbhost = 'localhost'; // mysql服务器主机地址
$dbuser = 'root'; // mysql用户名
$dbpass = 'root'; // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('连接失败: ' . mysqli_error($conn));
}
// 执行查询
?>
2、执行多表查询语句
// 设置编码,防止中文乱码
mysqli_query($conn , "set names utf8");
// 多表查询
$sql = 'select * from table1,table2';
mysqli_select_db( $conn, 'DEMO' );
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('无法读取数据: ' . mysqli_error($conn));
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
echo $row;
}
mysqli_close($conn);
更多多表查询的方法:
1、普通方法
select * from table1,table2
2、left join right join 等方法
select * from table1 t1 left join table2 t2 on t1.id = t2.id
3、UNION 方法
select * from table1 union select * from table2
4、嵌套查询方法
select * from table1 where id in (select pid from table2 where pid > 10)
以上就是php实现多表查询的具体操作,代码详细清楚,如果在日常工作遇到这个问题,希望你能通过这篇文章解决问题。如果想了解更多相关内容,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。