SELECT wrzm,mysh,sgbh FROM ( SELECT count(*) wrzm,0 mysh,0 sgbh FROM user_witness WHERE plan_uid = 123456 UNION ALL SELECT 0 wrzm,count(*) mysh,0 sgbh FROM user_relation WHERE other_uid = 123456 UNION ALL SELECT 0 wrzm,0 mysh,count(*) sgbh FROM plan_stage WHERE uid = 123456 AND status = 1) t;
我们发现这个结果已经有点像样了,如果能将表中 wrzm ,mysh ,sgbh 的数据三行变成一行,那就好了。于是我们很自然可以想到用 SUM (当然一开始我没想到,经过朋友提醒),于是改写上面的 SQL :
12345678910111213
SELECT sum(wrzm) wrzm,sum(mysh) mysh,sum(sgbh) sgbh FROM ( SELECT count(*) wrzm,0 mysh,0 sgbh FROM user_witness WHERE plan_uid = 123456 UNION ALL SELECT 0 wrzm,count(*) mysh,0 sgbh FROM user_relation WHERE other_uid = 123456 UNION ALL SELECT 0 wrzm,0 mysh,count(*) sgbh FROM plan_stage WHERE uid = 123456 AND status = 1) t;
SELECT uid,sum(wrzm) wrzm,sum(mysh) mysh,sum(sgbh) sgbh FROM ( SELECT plan_uid uid,count(*) wrzm,0 mysh,0 sgbh FROM user_witness GROUP BY plan_uid UNION ALL SELECT other_uid uid,0 wrzm,count(*) mysh,0 sgbh FROM user_relation GROUP BY other_uid UNION ALL SELECT uid,0 wrzm,0 mysh,count(*) sgbh FROM plan_stage WHERE status = 1 GROUP BY uid) t GROUP BY uid;
查询结果为:
mysql_count_results_3
在这个结果中,如果我们需要查看具体某一个用户,那么在最后加上 WHERE uid = 123456 即可,如果要排序的话,那么直接加上 ORDER BY 即可。
文明上网理性发言!