join的类型
简单介绍下内外连接的做法
1. 内联结:将两个表中存在联结关系的字段符合联结关系的那些记录形成记录集的联结。
2. 外联结:分为外左联结和外右联结
NAME_EMPLOYEE |
yoyo |
golyoung |
NAME_MANAGER |
ychen |
golyoung |
内链接查询语句
select * from NAME_EMPLOYEE, NAME_MANAGER where NAME_EMPLOYEE.name = NAME_MANAGER.name;(table_reference条目中的每个逗号都看作相当于一个内部联合)
SELECT * FROM NAME_EMPLOYEE JOIN NAME_MANAGER ON NAME_EMPLOYEE.name= NAME_MANAGER.name; SELECT * FROM NAME_EMPLOYEE INNER JOIN NAME_MANAGER ON NAME_EMPLOYEE.name = NAME_MANAGER.name; SELECT * FROM NAME_EMPLOYEE CROSS JOIN NAME_MANAGER ON NAME_EMPLOYEE.name = NAME_MANAGER.name; SELECT * FROM NAME_EMPLOYEE STRAIGHT_JOIN NAME_MANAGER ON NAME_EMPLOYEE.name = NAME_MANAGER.name;
查询结果只显示一条golyoung golyoung的数据,因为这个数据满足查询条件,2张表都有这个数据。
- 默认的JOIN都是INNER JOIN
- CROSS JOIN从语法上说与INNER JOIN等同
- STRAIGHT_JOIN与JOIN相同。除了有一点不一样,左表会在右表之前被读取。STRAIGH_JOIN可以被用于这样的情况,即联合优化符以错误的顺序排列表。
外联结
SELECT * FROM NAME_EMPLOYEE LEFT JOIN NAME_MANAGER ON NAME_EMPLOYEE.name=NAME_MANAGER.name;
查询结果是
+----------+-----------+ | name | name | +----------+-----------+ |yoyo | NULL | | golyoung | golyoung | +-----------+----------+
右联结 使用right join, 结果相反。