加入没有重复

时间:2018-04-10 16:40:29

标签: sql left-join

我正在运行此查询以获取与家庭相关联的人员和宠物的列表,但是查询返回的行等于与家庭相关联的人和宠物数量的乘积而不是总和。我基本上试图在1中获得2个查询。贝娄是测试数据,观察到的行为和预期行为的一个例子。

SELECT * 
FROM households 
LEFT JOIN pets 
  ON households.house_id = pets.house_id 
LEFT JOIN people 
  ON households.house_id = people.house_id 
WHERE households.house_id IN ("5");

表:

HOUSEHOLDS
house_id name
5        foo
6        bar    

PEOPLE
person_id  house_id
333        5
444        5    


PETS
pet_name   house_id
boo        5
bii        5
baa        5    


RESULT (6 rows, 2*3)
house_id name person_id house_id pet_name house_id
5        foo  333       5        boo      5
5        foo  444       5        boo      5
5        foo  333       5        bii      5
5        foo  444       5        bii      5
5        foo  333       5        baa      5
5        foo  444       5        baa      5 

EXPECTED (5 rows, 2+3)
house_id name person_id house_id pet_name house_id
5        foo  NULL      NULL     boo      5
5        foo  NULL      NULL     bii      5
5        foo  NULL      NULL     baa      5
5        foo  333       5        NULL     NULL
5        foo  444       5        NULL     NULL

1 个答案:

答案 0 :(得分:0)

您意识到JOIN相当于乘法*

您需要使用UNION相当于添加+

SELECT h.house_id, h.name, 
       p1.person_id, 
       p1.house_id,
       null as pet_name,
       null as house_id
FROM households h
LEFT JOIN people p1
  ON h.house_id = p1.house_id 
WHERE h.house_id IN ("5")

UNION ALL

SELECT h.house_id, h.name, 
       null as person_id, 
       null as house_id,
       p2.pet_name,
       p2.house_id
FROM households h
LEFT JOIN pets p2
  ON h.house_id = p2.house_id 
WHERE h.house_id IN ("5")