马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
一、毗连--用于归并数据库中两个或多个表中的纪录
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
|