我有下表。
Owner_id Owner
-----------------
1 Bill
2 Steve
Animal Owner_fk_id
-----------------------
Cat 1
Dog 1
Lion 2
Car Owner_fk_id
-----------------------
Ferrari 1
BMW 1
Lotus 2
我希望列出所有动物和汽车,对于拥有至少1辆法拉利车主的车主。由于比尔拥有法拉利,我们将列出所有比尔的汽车和动物。
如果我使用以下SQL:
SELECT *
FROM Owner
LEFT JOIN Animal ON (Animal.Owner_fk_id = Owner.Owner_id )
LEFT JOIN Car ON (Car.Owner_fk_id = Owner.Owner_id )
WHERE Car.Car = 'Ferrari'
我将会
Owner Animal Car
---------------------------
Bill Cat Ferrari
Bill Dog Ferrari
我希望的结果是什么
Owner Animal Car
---------------------------
Bill Cat Ferrari
Bill Cat BMW
Bill Dog Ferrari
Bill Dog BMW
我可以知道我应该使用的正确SQL语句是什么吗?
答案 0 :(得分:3)
根据您所需的条件进行内部联接(即Car='Ferrari
),然后像以前一样加入其他表格。
SELECT o.Owner, a.Animal, c2.Car
FROM Owner as o
INNER JOIN Car as c1 on c1.Owner_fk_id = o.Owner_id and c1.Car='Ferrari'
LEFT JOIN Animal as a ON a.Owner_fk_id = o.Owner_id
LEFT JOIN Car as c2 ON c2.Owner_fk_id = o.Owner_id;
答案 1 :(得分:0)
如果一个Owner
拥有多辆法拉利而且只计算一次他/她很重要,你可以这样做:
SELECT subq.Owner, a.Animal, c2.Car FROM
(SELECT o.* FROM Owner as o1 WHERE EXISTS
(SELECT 1 FROM Car as c1
WHERE c1.Owner_fk_id = o1.Owner_id
AND c1.Car='Ferrari')
) as subq
LEFT JOIN Animal as a ON a.Owner_fk_id = subq.Owner_id
LEFT JOIN Car as c2 ON c2.Owner_fk_id = subq.Owner_id;