我需要在多个列中找到三个最频繁的数字(分别为S1,S2,S3,S4,S5和S6)。我知道我可以使用“全部联盟”来做到这一点,但是我无法使其正常工作。另外,与$ id对应的数字必须存在于列之一中,但应从最频繁的数字列表中排除。我已经尝试了以下代码,但其中不包含$ id:
我实际上还需要一件事。必须有一个where子句,其中还必须包含“ where matchmal.goal ='0'”。
SELECT tag, COUNT(*)
FROM (
SELECT s1 AS tag from matchmal
UNION ALL
SELECT s2 AS tag from matchmal
UNION ALL
SELECT s3 AS tag from matchmal
UNION ALL
SELECT s4 AS tag from matchmal
UNION ALL
SELECT s5 AS tag from matchmal
UNION ALL
SELECT s6 AS tag from matchmal
) AS X (tag)
GROUP BY tag
ORDER BY COUNT(*) DESC
我认为这应该作为数据库示例:
如果$ id为'91',则输出应为数字13和15,因为它们是最常见的数字(它们同时存在于两行中)。
答案 0 :(得分:0)
根据您的要求使用UNION
SELECT * from (
SELECT goal, s1 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s1
UNION
SELECT goal, s2 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s2
UNION
SELECT goal, s3 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s3
UNION
SELECT goal, s4 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s4
UNION
SELECT goal, s5 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s5
UNION
SELECT goal, s6 AS tag, count(1) AS qty FROM `matchmal` where 91 IN (s1, s2, s3, s4, s5, s6) GROUP BY s6
) temp WHERE tag != 91 AND qty > 1
ORDER BY qty DESC
预期的输出结果:
goal tag qty
0 13 2
0 15 2