2013-12-08 65 views
0

我有兩個表格「user」和「user_things」。我想讓所有的用戶都有一件或多件事情,但我不想自己檢索這些東西(我只希望每個用戶返回一行)。如何在沒有選擇的情況下進行左連接

Table 1: 
id 
username 

Table 2: 
id 
userid 
thingname 

例如:我想找到所有用戶使用「帽子」和「汽車」。如果有兩個用戶,我只想返回兩行(不是4)。

+0

使用exists(兩次),喜歡這裏:http://stackoverflow.com/a/20452973/905902 – wildplasser

回答

1

在另一個表格中選擇所有記錄'汽車'和'帽子'exists的用戶。

select 
    * 
from 
    User u 
where 
    exists (
    select 'x' 
    from Things t 
    where t.userid = u.id and t.thingname = 'hat') and 
    exists (
    select 'x' 
    from Things t 
    where t.userid = u.id and t.thingname = 'car') 

或者,您也可以做到這一點,但我認爲這是不太好的,少語義正確:

select distinct 
    u.* 
from 
    Users u 
    inner join Things tc on tc.userid = u.id and tc.thingname = 'car' 
    inner join Things th on th.userid = u.id and th.thingname = 'hat' 

甚至:

select 
    u.* 
from 
    Users u 
where 
    (select 
    count('x') 
    from Things t 
    where t.userid = u.id and t.thingname in ('car', 'hat')) = 2 

儘管最後一個也可能會返回用戶沒有汽車和兩個帽子。

2

使用聚合:

select u.userid, u.username 
from user u join 
    user_things ut 
    on ut.userid = u.id 
group by t1.userid, t1.username 
having sum(case when ut.thingname = 'hat' then 1 else 0 end) > 0 and 
     sum(case when ut.thingname = 'car' then 1 else 0 end) > 0 

having條款的第一部分計算的「帽子」的數量。其次是「汽車」的數量。 >條件要求兩者都存在。

2

一個簡單的辦法是

select user.id, user.name 
    from user 
inner join things t on t.userid = user.id 
where t.thingname in ('car', 'hat') 
group by user.id, user.name 
having count(*) >= 2; -- (2 for 'car' and 'hat', 3 for 'car', 'hat' and 'bike', ...) 

SQL Fiddle

相關問題