内连接,外连接与交叉连接
内连接,外连接与交叉连接用于测试的表结构及数据,在PostgresQL中测试通过。
Weather表:
city | temp_lo | temp_hi | prcp | date
---------------+---------+---------+------+------------
San Francisco | 46 | 50 | 0.25 | 1994-11-27
Hayward | 54 | 37 | | 1944-11-29
San Francisco | 45 | 67 | 0.8 | 2012-02-23
Cities表:
name | loction
---------------+-----------
San Francisco | (-194,53)
beijing | (123,45)
一,内连接
内连接就和一般的联合查询一样,会返回符合条件的结果集。
内连接分为:
1.等值连接,以‘=’作为连接查询条件----SELECT * FROM weather AS w INNER JOIN cities AS c ON w.city = c.name;
查询结果:
city | temp_lo | temp_hi | prcp | date | name | loction
---------------+---------+---------+------+------------+-------------- San Francisco | 46 | 50 | 0.25 | 1994-11-27 | San Francisco | (-194,53)
San Francisco | 45 | 67 | 0.8 | 2012-02-23 | San Francisco | (-194,53)
2.不等连接,以‘<>,>,<,>=,<=,!>,!<’作为连接查询条件----SELECT * FROM weather AS w INNER JOIN cities AS c ON w.city <> c.name;
二,外连接
外连接会根据连接类型保留其中一个表,或两个表中不符合查询条件的结果集。
外连接分为:
1.左外连接,(LEFT JOIN或者LEFT OUTER JOIN)会保留左表中不符合条件的结果,没有值的列会用NULL值替代----
SELECT * FROM weather AS w LEFT OUTER JOIN cities AS c ON (w.city = c.name);
查询结果:
"San Francisco";46;50;0.25;"1994-11-27";"San Francisco";"(-194,53)"
"Hayward";54;37; ;"1944-11-29";"";""
"San Francisco";45;67;0.8;"2012-02-23";"San Francisco";"(-194,53)"
2.右外连接,(RIGHT JOIN 或者 RIGHT OUTER JOIN)会保留右表中不符合条件的结果,没有的值会用NULL值替代----SELECT * FROM weather AS w RIGHT JOIN cities AS c ON (w.city = c.name);
"San Francisco";45;67;0.8;"2012-02-23";"San Francisco";"(-194,53)"
"San Francisco";46;50;0.25;"1994-11-27";"San Francisco";"(-194,53)"
"";;;;"";"beijing";"(123,45)"
3.全外连接,(FULL JOIN)显示符合条件的数据行,同时显示左右不符合条件的数据行,相应的左右两边显示NULL----SELECT * FROM weather AS w FULL JOIN cities AS c ON (w.city = c.name);
查询结果:
"";;;;"";"beijing";"(123,45)"
"Hayward";54;37;;"1944-11-29";"";""
"San Francisco";46;50;0.25;"1994-11-27";"San Francisco";"(-194,53)"
"San Francisco";45;67;0.8;"2012-02-23";"San Francisco";"(-194,53)"
三.交叉连接
交叉连接(CROSS JOIN)返回两个表的笛卡尔集
SELECT * FROM weather CROSS JOIN cities;
查询结果:
"San Francisco";46;50;0.25;"1994-11-27";"San Francisco";"(-194,53)"
"San Francisco";46;50;0.25;"1994-11-27";"beijing";"(123,45)"
"Hayward";54;37;;"1944-11-29";"San Francisco";"(-194,53)"
"Hayward";54;37;;"1944-11-29";"beijing";"(123,45)"
"San Francisco";45;67;0.8;"2012-02-23";"San Francisco";"(-194,53)"
"San Francisco";45;67;0.8;"2012-02-23";"beijing";"(123,45)"