我有一个mysql表,根据他们选择的图片(pic1,pic2或pic3)记录用户ID。我希望能够打印出同一行中最常见的两个用户ID,无论他们选择哪张图片。
在下表中,答案将是4和6,因为它们最常见于同一行。我无法弄清楚如何构建一个可以执行此操作的查询,我认为唯一的方法可能是使用多查询,但我想出了如何构建它们。任何人都可以帮助我吗?
pic1 | pic2 | pic3
-------------------------------------
4 null 6
6 4 null
4 9 null
6 null 4
我想我的查询的第一部分看起来像这样但接着是什么?:注意$ userid是登录用户。
"SELECT pic1, pic2, pic3 FROM mytable where pic1='$userid' OR pic2='$userid' OR pic3='$userid'";
答案 0 :(得分:1)
这应该会给你正确的结果:
SELECT LEAST(p1, p2) AS p1, GREATEST(p1,p2) AS p2
FROM (
SELECT pic1 AS p1, pic2 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic2 IS NOT NULL
UNION ALL
SELECT pic1 AS p1, pic3 AS p2
FROM mytable WHERE pic1 IS NOT NULL AND pic3 IS NOT NULL
UNION ALL
SELECT pic2 AS p1, pic3 AS p2
FROM mytable WHERE pic3 IS NOT NULL AND pic2 IS NOT NULL
) s
GROUP BY LEAST(p1, p2), GREATEST(p1,p2)
ORDER BY COUNT(*) DESC
LIMIT 1
答案 1 :(得分:0)
如果每一行只有两个不同的用户,您可以使用此查询来获取所有有序的用户对以及他们一起出现的次数:
SELECT mn, mx, COUNT(*)
FROM (select if(pic1 is null, least(pic2, pic3), least(pic1, coalesce(pic2, pic3))) mn,
if(pic1 is null, greatest(pic2, pic3), greatest(pic1, coalesce(pic2, pic3))) mx
from t) x
GROUP BY mn, mx
ORDER BY count(*) DESC;
请注意,如果值为NULL,则最小和最大函数返回NULL,这就是为什么if和coalesce函数是必要的。
要仅获得具有最大计数的用户对,查询将更长:
SELECT mn, mx, count(*) cnt
FROM (select if(pic1 is null, least(pic2, pic3), least(pic1, coalesce(pic2, pic3))) mn,
if(pic1 is null, greatest(pic2, pic3), greatest(pic1, coalesce(pic2, pic3))) mx
from t) x
GROUP BY mn, mx
HAVING count(*) = (select max(cnt) from (SELECT mn, mx, count(*) cnt
FROM (select if(pic1 is null, least(pic2, pic3), least(pic1, coalesce(pic2, pic3))) mn,
if(pic1 is null, greatest(pic2, pic3), greatest(pic1, coalesce(pic2, pic3))) mx
from t) x
GROUP BY mn, mx) y);
请参阅fiddle