从今天开始, 小白我将带领大家一起来补充一下 数据库的知识.
自连接 (Self Join) 是一种特殊的表连接. 自连接指相互连接的表在物理上同为一张表, 但是逻辑上是多张表. 自连接通常用于表中的数据有层次结构, 如区域表, 菜单表, 商品分类表等.
格式:
SELECT A.列名, B.列名 FROM 表A, 表B WHERE A.列名 = B.列名
数据:
例子: (过滤城市)
<?php $conn = mysqli_connect("localhost", "root","admin","study"); if ($conn) { echo "数据库链接成功\n"; } else { echo mysqli_connect_error(); } # SQL语句 $SQL = "SELECT * FROM location WHERE pid <> 0"; # 执行 $result = mysqli_query($conn, $SQL); # 查看是否执行成功 if ($result) { echo "SQL 语句执行成功!\n"; }else { echo mysqli_error($conn); } # 调试输出 while ($line = mysqli_fetch_assoc($result)) { print_r($line); } # 关闭连接 mysqli_close($conn); ?>
输出结果:
数据库链接成功 SQL 语句执行成功! Array ( [id] => 2 [pid] => 1 [location] => 杭州 ) Array ( [id] => 3 [pid] => 1 [location] => 萧山 ) Array ( [id] => 5 [pid] => 2 [location] => 广州 ) Array ( [id] => 6 [pid] => 2 [location] => 台山 )
子查询又称为内部查询或嵌套查询. 它允许我们在 WHERE 子句中过滤某个字段的多个值.
格式:
SELECT 列名 FROM 表名 WHERE 列名 IN ( SELECT 列名 FROM 表名 [条件])
数据 (table1):
数据 (table2):
例子:
<?php $conn = mysqli_connect("localhost", "root","admin","study"); if ($conn) { echo "数据库链接成功\n"; } else { echo mysqli_connect_error(); } # SQL语句 $SQL = "SELECT table1.* FROM table1 WHERE table1.name in (SELECT table2.name FROM table2)"; # 执行 $result = mysqli_query($conn, $SQL); # 查看是否执行成功 if ($result) { echo "SQL 语句执行成功!\n"; }else { echo mysqli_error($conn); } # 调试输出 while ($line = mysqli_fetch_assoc($result)) { print_r($line); } # 关闭连接 mysqli_close($conn); ?>
输出结果:
数据库链接成功 SQL 语句执行成功! Array ( [id] => 1 [name] => 杨富贵 [age] => 18 ) Array ( [id] => 2 [name] => 杨美丽 [age] => 19 ) Array ( [id] => 3 [name] => 杨建国 [age] => 20 )
EXISTS 是子查询中用于测试内部查询是否返回任何行的布尔运算符.
格式:
SELECT 列名 FROM 表名 WHERE EXISTS
例子:
<?php $conn = mysqli_connect("localhost", "root","admin","study"); if ($conn) { echo "数据库链接成功\n"; } else { echo mysqli_connect_error(); } # SQL语句 $SQL = "SELECT table1.* FROM table1 WHERE EXISTS (SELECT table2.name FROM table2 WHERE table1.name = table2.name)"; # 执行 $result = mysqli_query($conn, $SQL); # 查看是否执行成功 if ($result) { echo "SQL 语句执行成功!\n"; }else { echo mysqli_error($conn); } # 调试输出 while ($line = mysqli_fetch_assoc($result)) { print_r($line); } # 关闭连接 mysqli_close($conn); ?>
输出结果:
数据库链接成功 SQL 语句执行成功! Array ( [id] => 1 [name] => 杨富贵 [age] => 18 ) Array ( [id] => 2 [name] => 杨美丽 [age] => 19 ) Array ( [id] => 3 [name] => 杨建国 [age] => 20 )