MySQL 联表查询
关系型数据库,免不了表之间存在各种引用与关联。这些关联是通过主键与外键搭配来形成的。所以,取数据时,很大情况下单张表无法满足需求,额外的数据则需要将其他表加入到查询中来,这便是
多表联合查询时,可省略 JOIN 关键字,以逗号分隔多张表,此时默认会当作 INNER JOIN 来处理。比如, SELECT table1.*,
table2.*
FROM table1,
table2; 等效于: SELECT table1.*,
table2.*
FROM table1
INNER JOIN table2;
需要注意的是,当逗号形式与其他联表关键词结合时,在指定了联表条件,比如通过
SELECT left_tbl.*
FROM left_tbl LEFT JOIN right_tbl ON left_tbl.id = right_tbl.id
WHERE right_tbl.id IS NULL; 通过此方法可方便地过滤出右边表中不符合条件的记录。
SELECT t1.name, t2.salary
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;
一条查询语句中的子查询必需取一个别名,这样才能在其他表达式中引用。 SELECT * FROM (SELECT 1, 2, 3) AS t1;
a LEFT JOIN b USING (c1, c2, c3)
一些 SELECT * FROM table1, table2;
考察下面的示例: CREATE TABLE t1 (i INT, j INT);
CREATE TABLE t2 (k INT, j INT);
INSERT INTO t1 VALUES(1, 1);
INSERT INTO t2 VALUES(1, 1);
SELECT * FROM t1 NATURAL JOIN t2;
SELECT * FROM t1 JOIN t2 USING (j); 查询结果: +------+------+------+
| j | i | k |
+------+------+------+
| 1 | 1 | 1 |
+------+------+------+
+------+------+------+
| j | i | k |
+------+------+------+
| 1 | 1 | 1 |
+------+------+------+ 结果中同名的列只出现一次,且都是值相同的那些记录。 通过向两表中插入一条新记录,令它们的 mysql> INSERT INTO t1 VALUES(2, 2);
Query OK, 1 row affected (0.00 sec)
a LEFT JOIN b USING (c1, c2, c3)
a LEFT JOIN b ON a.c1 = b.c1 AND a.c2 = b.c2 AND a.c3 = b.c3
COALESCE(a.c1, b.c1), COALESCE(a.c2, b.c2), COALESCE(a.c3, b.c3)
a.c1, a.c2, a.c3, b.c1, b.c2, b.c3
CREATE TABLE t1 (i1 INT);
CREATE TABLE t2 (i2 INT);
CREATE TABLE t3 (i3 INT); 针对上面的表,以下查询会报错: mysql> SELECT * FROM t1 JOIN t2 ON (i1 = i3) JOIN t3;
ERROR 1054 (42S22): Unknown column 'i3' in 'on clause' 而以下查询则可以: mysql> SELECT * FROM t1 JOIN t2 JOIN t3 ON (i1 = i3);
Empty set (0.00 sec) 因为此时 相关资源 |