2014-04-26 38 views
0

我正在努力應對此SQL查詢。說我有這兩個表選擇接收到的照片比發送照片更多的用戶

**USERS** 
+----+-------+ 
| id | name | 
+----+-------+ 
| 1 | james | 
| 2 | tom | 
| 3 | kate | 
+----+-------+ 

**PHOTOS** 
+-----------+-----------+---------+ 
| name | sent_from | sent_to | 
+-----------+-----------+---------+ 
| beach.jpg |   1 |  2 | 
| trees.jpg |   3 |  1 | 
| earth.jpg |   2 |  1 | 
+-----------+-----------+---------+ 

我怎麼能得到的,使用一個SQL查詢,所有與他們的ID比sent_from多個相關sent_to用戶?

+1

請給出您的嘗試 –

回答

1

兩倍彙總數據,然後做了比較:

select sf.sent_from 
from (select sent_from, count(*) as numsent 
     from photos 
     group by sent_from 
    ) sf left outer join 
    (select sent_to, count(*) as numrecv 
     from photos 
     group by sent_to 
    ) st 
    on sf.sent_from, st.sent_to 
where numsent > numrecv; 

如果你想用戶信息,然後加入。

另一種方法是先重構數據,然後再進行聚合:

select who 
from (select sent_from as who, 1 as sent_from, 0 as sent_to 
     from photos 
     union all 
     select sent_to as who, 0, 1 
     from photos 
    ) p 
group by who 
having sum(sent_from) > sum(sent_to); 
1

我覺得這裏的東西,可以幫助你:我認爲這

SELECT * FROM (
     SELECT `id`, `name`, 
     IFNULL((SELECT count(*) FROM `photos` WHERE `sent_from` = `users`.`id`),0) AS `sent_from_count`, 
     IFNULL((SELECT count(*) FROM `photos` WHERE `sent_t`o = `users`.`id`),0) AS `sent_to_count` 
     FROM `users`) AS `t1` 
    WHERE `t1`.`sent_to_count` > `t1`.`sent_to_count` 
+0

有幫助,謝謝! – superzamp