0

我有 table1(id, name), table2(id [FK to table1.id],user_id,visit)。对于每个table1.id,我需要从table1显示它的名称,计算用户并显示他们属于这个id的user_id,当table2.visit=1时,计算用户并显示他们属于这个id的user_id,当table2.visit= 0。此外,table1 中的某些 id 可能在 table2 中不存在,对于这些 id,我希望在计数器中有 0。

结果表应如下所示:

id|name|count_visitors|list_of_visitors_id|count_non_visitors|list_of_non_visitors_id|
1 |a   |2             |5,10               |1                 |4                      |

你能帮忙查询一下吗?

4

1 回答 1

1
SELECT t1.name, 
       COALESCE( visitors.visitors_count, 0) AS `count_visitors`,
       COALESCE( visitors.visitors_list, '') AS `list_of_visitors_id`, 
       COALESCE( nonvisitors.nonvisitors_count, 0 ) AS `count_non_visitors`,
       COALESCE( nonvisitors.nonvisitors_list, '') AS `list_of_non_visitors_id`
FROM table1 t1
LEFT JOIN
( SELECT id, GROUP_CONCAT( user_id ) AS visitors_list, COUNT(*) AS visitors_count
    FROM table2
    WHERE visit = 1
    GROUP BY id ) visitors
ON t1.id = visitors.id
LEFT JOIN
  ( SELECT id, GROUP_CONCAT( user_id ) AS nonvisitors_list, COUNT(*) AS nonvisitors_count
    FROM table2
    WHERE visit = 0
    GROUP BY id ) nonvisitors
ON t1.id = nonvisitors.id

自己试试:Sqlfiddle

如果您需要一位用户使用它,只需在末尾添加一行:

WHERE t1.id = 1
于 2013-04-30T22:16:44.457 回答