来自许多表的MySQL请求计数

时间:2012-02-28 20:07:20

标签: mysql count request

我有表table_one, table_two, table_three, table_four所有结构大致相同。 它有id, name, status, user_id列。

i.g。除了table_four之外,我在每个表中都有多次使用user_id 345的用户John。并且status对于某些被告是1而其他条目是0

现在我需要用一个查询来计算每个表中该用户的状态是多少次。

所以我这样做:

SELECT table_one.user_id,
   SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone
   SUM(CASE WHEN table_two.status = 1 THEN 1 ELSE 0 END) AS count_tbltwo
   SUM(CASE WHEN table_three.status = 1 THEN 1 ELSE 0 END) AS count_tblthree
   SUM(CASE WHEN table_four.status = 1 THEN 1 ELSE 0 END) AS count_tblfour
FROM table_one
   LEFT JOIN table_one   ON table_one.user_id   = table_one.user_id
   LEFT JOIN table_two   ON table_two.user_id   = table_one.user_id
   LEFT JOIN table_three ON table_three.user_id = table_one.user_id
   LEFT JOIN table_four  ON table_four.user_id  = table_one.user_id

WHERE tbl_one.user_id = 345

问题是请求输出4,0,0,0时应该是2,1,1,0

如果我离开SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone - count_tblone将等于4,即使在table_one - status字段等于1的用户345的两个记录中也是如此。

1 个答案:

答案 0 :(得分:0)

打字的次数要多得多,但我建议使用UNION,,特别是如果用户可能不在table_one 中。

SELECT
   SUM(count_tblone) AS count_tblone,
   SUM(count_tbltwo) AS count_tbltwo,
   SUM(count_tblthree) AS count_tblthree,
   SUM(count_tblfour) AS count_tblfour
FROM (
   SELECT 
      SUM(CASE WHEN table_one.status = 1 THEN 1 ELSE 0 END) AS count_tblone,
      0 AS count_tbltwo,
      0 AS count_tblthree,
      0 AS count_tblfour
   FROM table_one
   WHERE tbl_one.user_id = 345
   UNION
   SELECT 
      0 AS count_tblone,
      SUM(CASE WHEN table_two.status = 1 THEN 1 ELSE 0 END) AS count_tbltwo,
      0 AS count_tblthree,
      0 AS count_tblfour
   FROM table_two
   WHERE tbl_one.user_id = 345
   UNION

......表3和4 ...

) AS tblMyUnionedTables