我已经搜索过,但我找不到我想要的东西。
我有两张桌子:
表1
| d | text |
| 101 | 'description 101' |
| 102 | 'description 102' |
| 103 | 'description 103' |
表2
| id | d1 | d2 | d3 | d4 |
| 01 | 104 | 242 | 102 | 222 |
| 02 | 423 | 553 | | |
| 03 | 832 | 142 | 102 | |
等
我想要计算Table1中每个“d”用作表2中的d1,d2,d3和d4的次数。输出看起来像这样:
| d | count_d1 | count_d2 | count_d3 | count_d4 |
| 101 | 30032 | 108 | 5002 | 392 |
| 102 | 440 | 5330 | 24 | 5 |
| 103 | 0 | 309 | 2220 | 4 |
等
我确信有一些显而易见的东西,我只是没想到,但我现在已经看了一个多小时了,而且我迷失在一连串的连接和子查询中。
答案 0 :(得分:1)
SELECT t1.d,
(
SELECT COUNT(*)
FROM Table2 s2a
WHERE s2a.d1 = t1.d
) AS count_d1,
(
SELECT COUNT(*)
FROM Table2 s2b
WHERE s2b.d2 = t1.d
) AS count_d2,
(
SELECT COUNT(*)
FROM Table2 s2c
WHERE s2c.d3 = t1.d
) AS count_d3,
(
SELECT COUNT(*)
FROM Table2 s2d
WHERE s2d.d4 = t1.d
) AS count_d4
FROM Table1 as t1
答案 1 :(得分:0)
您必须将其拆分为4个查询(每列1个)
SELECT d, sum(Count_d1), sum(Count_d2), sum(Count_d3), sum(Count_d4) FROM (
SELECT d, count(1) AS Count_d1, null AS Count_d2, null AS Count_d3, null AS Count_d4 FROM Table1 LEFT JOIN Table2 on Table1.d=Table2.d1
UNION ALL
SELECT d, null AS Count_d1, count(1) AS Count_d1, null AS Count_d3, null AS Count_d4 FROM Table1 LEFT JOIN Table2 on Table1.d=Table2.d2
UNION ALL
SELECT d, null AS Count_d1, null AS Count_d2, count(1) AS Count_d3, null AS Count_d4 FROM Table1 LEFT JOIN Table2 on Table1.d=Table2.d3
UNION ALL
SELECT d, null AS Count_d1, null AS Count_d2, null AS Count_d3, count(1) AS Count_d4 FROM Table1 LEFT JOIN Table2 on Table1.d=Table2.d4
) GROUP BY d
答案 2 :(得分:0)
您可以通过多个别名JOIN条件来完成此操作,如下所示:
SELECT
Table1.d,
COUNT(d1.id) AS d1,
COUNT(d2.id) AS d2,
COUNT(d3.id) AS d3,
COUNT(d4.id) AS d4
FROM
Table1
LEFT JOIN
Table2 d1 ON
Table1.d = d1.D1
LEFT JOIN
Table2 d2 ON
Table1.d = d2.D2
LEFT JOIN
Table2 d3 ON
Table1.d = d3.D3
LEFT JOIN
Table2 d4 ON
Table1.d = d4.D4
GROUP BY Table1.d
这将允许您避免对表的多个单值调用的开销,同时保留单个查询。