加入两个表并统计

时间:2014-05-24 09:36:11

标签: mysql sql

我有这种结构

kode数据

+------------+-----------+
| code | ket             |
+------------+-----------+
|20401 | code one        |
|21401 | code two        |
|22401 | code three      |
|etc   | etc             |
+------------------------+
+-----+-----------------+-----------+
| id  | code1           | code2     |
+-----+-----------------+-----------+
|1    | 20401           | 21402     |
|2    | 21401           | 22401     |
|3    | 22401           | 20401     |
|4    | 20401           | 21401     |
+-----------------------+-----------+

如何计算和总和以实现如下输出

+-----------+-------------+-------------+ |code | count code1 | count code2 | +-----------+-------------+-------------+ |code one | 2 | 1 | |code two | 1 | 1 | |code three | 3 | 1 | |etc | etc | etc | +-----------+-------------+-------------+

基本上我想要的是选择表 ket 并计入 code1 code2 ,只需一个查询即可获得代码。

1 个答案:

答案 0 :(得分:3)

您可以执行两个连接:

SELECT    ket AS code, 
          cnt1 AS "count code1"
          cnt2 AS "count code2"
FROM      kode
LEFT JOIN (SELECT   code1, COUNT(*) AS cnt1
           FROM     data
           GROUP BY code1) c1 ON kode.code = c1.code1
LEFT JOIN (SELECT   code2, COUNT(*) AS cnt2
           FROM     data
           GROUP BY code2) c2 ON kode.code = c2.code2