4

是否可以添加和乘以 id 相同的不同表的计数?想象:

Table_1       Table_2    Table_3
id            id         id
1             1          1
1             2          2
2             2          3
3             2          3
3             2          3
3             3          3

所以最终结果将是这个有 2 列的表:

id        (COUNT(Table_1.id) + 2*COUNT(Table_2.id) + 3*COUNT(Table_3.id))
1                                   7
2                                   12
3                                   17
4

2 回答 2

2

我不知道我是否理解正确,但请尝试一下,

SELECT a.ID,
       a.aa + (2 * b.bb) + (3 * c.cc)
FROM
  (
    SELECT ID, COUNT(*) aa
    FROM table1
    GROUP BY ID
  ) a LEFT JOIN
  (
    SELECT ID, COUNT(*) bb
    FROM table2
    GROUP BY ID
  ) b ON a.ID = b.ID
  LEFT JOIN
  (
    SELECT ID, COUNT(*) cc
    FROM table3
    GROUP BY ID
  ) c ON a.ID = c.ID

SQLFiddle 演示

于 2012-10-18T16:13:26.193 回答
1
SELECT id, counts_1.number + 2 * counts_2.number + 3 * counts_3.number
FROM
(SELECT id, COUNT(*) AS number FROM Table_1 GROUP BY id) AS counts_1
JOIN
(SELECT id, COUNT(*) AS number FROM Table_2 GROUP BY id) AS counts_2 USING (id)
JOIN
(SELECT id, COUNT(*) AS number FROM Table_3 GROUP BY id) AS counts_3 USING (id)

请注意,此解决方案要求每个 id 在每个表中至少存在一次,否则它将被排除在结果之外。改变这一点需要 MySQL 无法实现的 FULL OUTER JOIN。不过,有一些方法可以绕过这个限制

于 2012-10-18T16:13:20.893 回答