对于 tableA xxx join tableB,tableA称为左表,tableB称为右表:
本文内容以下述数据举例说明:
tableA与tableB:
tableA tableB
aid name bid value
1 2000 1 2010
2 2001 2 2012
3 2003 4 2014
5 2005 8 2016
1.inner join(内联结)
返回两个表中联结字段相等的行:
SELECT * FROM tableA inner join tableB on tableA.ID =tableB.ID;
则结果为:
aid name bid value
1 2000 1 2010
2 2001 2 2012
2.left join(左联结)
返回包括左表中的所有记录,以及右表中联结字段与左表中相等的记录
SELECT * FROM tableA left join tableB on tableA.ID =tableB.ID;
则结果为:
aid name bid value
1 2000 1 2010
2 2001 2 2012
3 2003
5 2005
3.right join(右联结)
返回包括右表中的所有记录,以及左表中联结字段与右表中相等的记录
SELECT * FROM tableA right join tableB on tableA.ID =tableB.ID;
则结果为:
aid name bid value
1 2000 1 2010
2 2001 2 2012
4 2014
8 2016
4.full join
返回左右表中的所有记录,联结字段相同的和不同的都列出来:
SELECT * FROM tableA full join tableB on tableA.ID =tableB.ID;
则返回结果为:
aid name bid value
1 2000 1 2010
2 2001 2 2012
3 2003
5 2005
4 2014
8 2016
注意.
还有一种cross join(笛卡尔积)
返回左右表联结字段的的所有组合项(N*M项)
SELECT * FROM tableA cross join tableB
则返回结果为:
aid name bid value
1 2000 1 2010
1 2000 2 2012
1 2000 4 2014
1 2000 8 2016
2 2001 1 2010
2 2001 2 2012
2 2001 4 2014
2 2001 8 2016
3 2003 1 2010
3 2003 2 2012
3 2003 4 2014
3 2003 8 2016
5 2005 1 2010
5 2005 2 2012
5 2005 4 2014
5 2005 8 2016
本文综合参考: