如何计算在5到6列的另一个表中使用的一个表的主键?
如果table1
包含srno
列table2
,d1
,d2
,d3
中使用的主键d4
}。
我想计算srno=1,2,3,4
中使用table2
...等的次数。
有谁知道怎么做???
答案 0 :(得分:1)
以下查询将返回表2中列d1,d2,d3和d4中使用的每个值的次数(已更新):
SELECT table1.srno, SUM(cnt) FROM
table1,
(SELECT d1 AS srno, COUNT(d1) AS cnt FROM table2 GROUP BY d1
UNION ALL
SELECT d2 AS srno, COUNT(d2) AS cnt FROM table2 GROUP BY d2
UNION ALL
SELECT d3 AS srno, COUNT(d3) AS cnt FROM table2 GROUP BY d3
UNION ALL
SELECT d4 AS srno, COUNT(d4) AS cnt FROM table2 GROUP BY d4) AS cnt_tbl
WHERE table1.srno = cnt_tbl.srno
GROUP BY table1.srno
尝试小提琴here.
如果您只计算一个特定主键(例如1),请尝试
SELECT SUM(cnt) FROM
(SELECT COUNT(*) AS cnt FROM table2 WHERE d1 = 1
UNION ALL
SELECT COUNT(*) AS cnt FROM table2 WHERE d2 = 1
UNION ALL
SELECT COUNT(*) AS cnt FROM table2 WHERE d3 = 1
UNION ALL
SELECT COUNT(*) AS cnt FROM table2 WHERE d4 = 1) AS cnt_tbl
小提琴here。
或者没有UNION的更优雅的解决方案:
SELECT SUM(cnt) FROM
(SELECT ((d1=1) + (d2=1) + (d3=1) + (d4=1)) AS cnt
FROM table2
WHERE d1 = 1 OR d2= 1 OR d3 = 1 OR d4 = 1) AS cnt_tbl
(Fiddle)
答案 1 :(得分:0)