我有下一张桌子:
id| C1 | C2 | C3 | C4 | C5|
----------------------------
01| 23 | 19 | 30 | 30 | 30|
---------------------------
02| 23 | 40 | 30 | 30 | 30|
----------------------------
03| 23 | 20 | 19 | 30 | 30|
----------------------------
04| 23 | 19 | 30 | 30 | 30|
----------------------------
05| 23 | 23 | 23 | 19 | 30|
----------------------------
在此表中,数字19的计数为4
我需要一个查询来计算每个数字出现在表中的次数,搜索多个行和列,或至少用MySQL搜索数字。
答案 0 :(得分:2)
我union
所有列,然后只有count
值:
SELECT c, COUNT(*)
FROM (SELECT c1 AS c FROM my_table
UNION ALL
SELECT c2 FROM my_table
UNION ALL
SELECT c3 FROM my_table
UNION ALL
SELECT c4 FROM my_table
UNION ALL
SELECT c5 FROM my_table) t
GROUP BY c
答案 1 :(得分:1)
一种选择是将IF
与SUM
:
SELECT SUM(IF(id=19,1,0) + IF(c1=19,1,0) + IF(c2=19,1,0) +
IF(c3=19,1,0) + IF(c4=19,1,0) + IF(c5=19,1,0))
FROM YourTable
正如所指出的,实际上并不需要IF声明:
SELECT SUM((c1=19)+(c2=19)+(c3=19)+(c4=19))
FROM YourTable
答案 2 :(得分:0)
select count(*) FROM tablename where c1 = 19 OR c2 = 19 or c3 = 19 etc
答案 3 :(得分:0)
我更喜欢SUM方法:
SELECT SUM(
(t1.c1=x.num)
+ (t1.c2=x.num)
+ (t1.c3=x.num)
+ (t1.c4=x.num)
+ (t1.c5=x.num)
) count
FROM table1 t1
JOIN (SELECT 19 num) x