以下查询将返回 table2 中的 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
在这里尝试小提琴。
如果您只计算一个特定的主键(例如 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
在这里拉小提琴。
或者没有 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
(小提琴)