我有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。此外,table2中的某些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 |
你能帮忙查询吗?
答案 0 :(得分: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