当前位置:Gxlcms > PHP教程 > php如何实现多表查询

php如何实现多表查询

时间:2021-07-01 10:21:17 帮助过:42人阅读

php如何实现多表查询

多表联查就是要查询的结果是需要获取多个表的内容,把它们的关系建立为一个临时存在的表。

多表联合查询是不可以进行索引优化查询速度的,所以一般情况下不建议使用。

1、使用mysqli_connect连接数据库

  1. <?php
  2. header("Content-Type: text/html;charset=utf-8");
  3. $dbhost = 'localhost'; // mysql服务器主机地址
  4. $dbuser = 'root'; // mysql用户名
  5. $dbpass = 'root'; // mysql用户名密码
  6. $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
  7. if(! $conn )
  8. {
  9. die('连接失败: ' . mysqli_error($conn));
  10. }
  11. // 执行查询
  12. ?>

2、执行多表查询语句

  1. // 设置编码,防止中文乱码
  2. mysqli_query($conn , "set names utf8");
  3. // 多表查询
  4. $sql = 'select * from table1,table2';
  5. mysqli_select_db( $conn, 'DEMO' );
  6. $retval = mysqli_query( $conn, $sql );
  7. if(! $retval )
  8. {
  9. die('无法读取数据: ' . mysqli_error($conn));
  10. }
  11. while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
  12. {
  13. echo $row;
  14. }
  15. mysqli_close($conn);

更多多表查询的方法:

1、普通方法

  1. select * from table1,table2

2、left join right join 等方法

  1. select * from table1 t1 left join table2 t2 on t1.id = t2.id

3、UNION 方法

  1. select * from table1 union select * from table2

4、嵌套查询方法

  1. select * from table1 where id in (select pid from table2 where pid > 10)

更多PHP相关知识,请访问PHP中文网!

以上就是php如何实现多表查询的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行