一、连接--用于合并数据库中两个或多个表中的记录
1、两个连接表的查询
SELECT tb1_col1, tb1_col2, tb2_col4, tb_col2 FROM tb1, tb2 where tb1.col2=tb2.col2;
二、INNER JOIN--内连接检索两个表的交集
1、内连接两个表
SELECT tb1.col1, tb2.col2,... FROM tb_name tb1 INNER JOIN tb_name tb2 ON tb1.col = tb2.col; --内连接合并两个表进行条件查询
2、内连接多个表--按顺序两两执行,直到最后表连接
SELECT col1, col2, ...
FROM tb1
INNER JOIN tb2
ON condition1
INNER JOIN tb3
ON condition...
3、使用WHERE的内连接
SELECT col1, col2,...
FROM tb1
INNER JOIN tb2
ON tb1.col = tb2.col3
WHERE condition;
SELECT tb1.id, tb1.name, tb1.salary, tb2.address FROM cust_copy tb1 INNER JOIN customers tb2 ON tb1.name= tb2.name WHERE tb2.salary >=3000 ;
4、CROSS JOIN --交叉连接,将第一个表的每一行与第二个表的每一行合并,用于检索两个独立表(即排列)的笛卡尔积(或叉积)。
SELECT tb1.col, tb2.col,....FROM tb_name tb1 CROSS JOIN tb_name tb2;
二、外连接--外连接会检索两个表中的所有记录(分左连接、右连接和全连接)
1、LEFT JOIN --左连接,从第一个表检索所有记录,并将它们与第二个表中的记录进行匹配,(①如果左表中的记录在第二个表中没有对应记录,则添加 NULL 值。②如果第一个表中的记录数少于第二个表中的记录数,则第二个表中在第一个表中没有对应记录的记录将从结果中丢弃。)
SELECT tb1.col, tb2.col,...
FROM tb1_name tb1 LEFT JOIN tb2_name tb2
ON tb1.col = tb2.col;
SELECT tb1.id, tb1.name, tb1.salary, tb2.address FROM cust_copy tb1 LEFT JOIN customers tb2 ON tb1.name= tb2.name ;
1.1、也可以多个表进行左连接。第一个表作为完整表返回,而后面的表则与第一个表中的行匹配。如果记录不匹配,则返回 NULL。
1.2、使用WHERE进行左连接,进行条件判断限制
SELECT tb1.col, tb2.col2, tb3.col, ... FROM tb1_name tb1
LEFT JOIN tb2_name tb2 ON tb1.col = tb2.col
LEFT JOIN tb3_name tb3 ON tb1.col=tb3.col
WHERE condition;
2、RIGHT JOIN --右连接,右连接会返回右表的所有值,以及左表中匹配的值;如果没有匹配的连接谓词,则返回 NULL。
SELECT tb1.col, tb2.col,...
FROM tb1_name tb1 RIGTH JOIN tb2_name tb2
ON tb1.col = tb2.col;
SELECT tb1.id, tb1.name, tb1.salary, tb2.address FROM cust_copy tb1 RIGHT JOIN customers tb2 ON tb1.name= tb2.name ;
2.1、右连接也可以连接多个表。然而,不同的是,右连接返回的是整个第二个表,而不是第一个表。
2.2、使用WHERE 子句用于筛选出满足其指定条件的记录。
SELECT tb1.col, tb2.col2, tb3.col, ... FROM tb1_name tb1
RIGHT JOIN tb2_name tb2 ON tb1.col = tb2.col
RIGHT JOIN tb3_name tb3 ON tb2.col=tb3.col
WHERE condition;
3、全连接(UNION 或 UNION ALL 关键字模拟全连接操作),通过将两个表连接起来创建一个新表。连接后的表包含两个表的所有记录,并在两侧缺失的匹配项处填充 NULL。
SELECT tb1.col, tb2.col, ... FROM tb1_name tb1 LEFT JOIN tb2_name tb2 ON tb1.col = tb2.col
[UNION | UMION ALL]
SELECT tb1.col, tb2.col, ... FROM tb1_name tb1 RIGHT JOIN tb2_name tb2 ON tb1.col = tb2.col
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |