有 我有这张桌子'客户'那种自我参照。该表看起来像这样
customer
---------
id_cus name sex id_cus_family family_as
001 A M 002 son
002 B F 001 mother
003 C M 002 husband
004 D M 003 father
id_cus_family参考id_cus。我试图查询显示所有条目,并将其姓氏的名称添加为新列。我用过这个:
SELECT
c1.* , c2.name AS family_name
FROM
customer c1
inner join customer c2 on c2.id_cus = c1.id_cus_family
但结果并未显示来自客户表的所有条目。结果如下:
query result
---------
id_cus name sex id_cus_family family_as family_name
001 A M 002 son B
002 B F 001 mother A
002 B F 001 mother C
003 C M 003 husband D
它应该显示所有结果,对吧?或者我的查询代码有问题? 我非常感谢你的帮助。
答案 0 :(得分:2)
我修改了您的查询:
SELECT c1.*,c2.name as family_name
FROM Customer as c1
JOIN Customer as c2 ON c1.id_cus_family=c2.id_cus
结果如下:
id_cus name sex id_cus_family family_as family_name
1 A M 2 son B
2 B F 1 mother A
3 C M 2 husband B
4 D M 3 father C
答案 1 :(得分:0)
您可以使用Left outer join
SELECT
c1.* , c2.name AS family_name
FROM
customer c1
left outer join customer c2
on c2.id_cus = c1.id_cus_family