数据库连接查询
一、内连接(INNER JOIN 或者 JOIN)
(1)语法:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
或者
SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;
(2)举例:
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
INNER JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count;
或者
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count;
(3)结果:
在这里插入图片描述
(3)总结:
内联接使用比较运算符根据每个表共有的列的值匹配两个表中的行。
二、外连接(OUTER JOIN)
1、左外连接(LEFT JOIN)
(1)语法:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
或者 LEFT 和 JION中间加入一个OUTER,与INNER类似。
(2) 举例:
在websites.sql中加入一行数据7 stackoverflow hheoafhoaeghegho 0 IND(空格隔开,对应插入,就是随意的多插入了一个与另一张表的site_id对应不上的id)
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
LEFT JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count DESC;
(3)结果:
在这里插入图片描述
(4)总结:
根据条件Websites.id=access_log.site_id左表(Websites.sql)中有id为7而右表(Access_log.sql)中没有site_id为7的匹配行也会显示为null。LEFT JOIN从左表中返回所有行。
2、右外连接(RIGHT OUTER JOIN)
(1)语法:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
或者 RIGHT 和 JION中间加入一个OUTER,与INNER类似。
(2)举例:
SELECT Websites.name, access_log.count, access_log.date
FROM access_log
RIGHT JOIN Websites
ON access_log.site_id=Websites.id
ORDER BY access_log.count DESC;
或者 RIGHT 和 JION中间加入一个OUTER,与INNER类似。
(3)结果(结果和 上一个的结果一样,因为上一个的左表就是这个的右表,仔细看SQL语句)
(4)总结:
与左连接相反,右连接就是将右表(Websites.sql)的所有行返回。
3、全外连接(FULL OUTER JOIN)
(1)语法:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
(2)举例:
SELECT Websites.name, access_log.count, access_log.date
FROM Websites
FULL OUTER JOIN access_log
ON Websites.id=access_log.site_id
ORDER BY access_log.count DESC;
(3)结果:
MySQL中不支持FULL OUTER JOIN 可以通过左外连接和右外连接来实现。
SELECT
Websites.NAME,
access_log.count,
access_log.date
FROM
Websites
LEFT JOIN access_log ON Websites.id = access_log.site_id UNION
SELECT
Websites.NAME,
access_log.count,
access_log.date
FROM
Websites
RIGHT JOIN access_log ON Websites.id = access_log.site_id;
三、交叉连接(CROSS JOIN)
相当与笛卡尔积,左表和右表组合;