我有这样的SQL查询:
SELECT
CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
FROM
t1
LEFT JOIN t2 ON ...
LEFT JOIN t3 ON ...
LEFT JOIN t4 ON ...
val输出为:0,1,0,1,2,1或1,2,0,1,0,2,...(按随机顺序包括0,1,2)
我想要计算每个数字的总数,如:0 => 2,1 => 3,2 => 1,没有PHP代码
答案 0 :(得分:1)
您可以简单地将现有查询包装在子查询中,并创建一个计算事件的外部查询;
SELECT
LENGTH(val) - LENGTH(REPLACE(val, '0', '')) zeros,
LENGTH(val) - LENGTH(REPLACE(val, '1', '')) ones,
LENGTH(val) - LENGTH(REPLACE(val, '2', '')) twos
FROM (
SELECT
CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
FROM
t1
LEFT JOIN t2 ON ...
LEFT JOIN t3 ON ...
LEFT JOIN t4 ON ...
);
答案 1 :(得分:0)
您需要使用UNION ALL
。
SELECT tbl.col1, COUNT(tbl.col1)
FROM (
SELECT t1.a as col1
FROM t1
UNION ALL
SELECT t2.a as col1
FROM t2
UNION ALL
SELECT t3.a as col1
FROM t3
...
) tbl
GROUP BY tbl.col1;