时间:2021-07-01 10:21:17 帮助过:42人阅读
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相关知识,请访问PHP中文网!
以上就是php如何实现多表查询的详细内容,更多请关注Gxl网其它相关文章!