我正在努力解决这个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_to多于sent_from的所有用户?
答案 0 :(得分: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`
答案 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);