我有3张桌子。 user_sticker
保存用户之间发送的所有贴纸。加载配置文件视图屏幕时,我需要显示哪个是给用户最常见的标签。
用户
贴纸
user_sticker
因此,如果user_sticker
拥有此信息:
(这意味着用户254,362,519,945,199向用户205发送了贴纸)。 结果必须在同一记录中返回两者用户205信息(名称)和最常见的标签ID(在本例中为#3)。
答案 0 :(得分:1)
这将是选择:
select id_user_to, count(id_sticker) quant from user_sticker group by id_sticker order by quant desc limit 1;
现在有了用户的信息:JOIN
select us.id_user_to, u.name, count(us.id_sticker) quant
from user_sticker us
join user u on u.id_user=us.id_user_to
group by us.id_sticker
order by quant desc limit 1;
答案 1 :(得分:1)
好的,让我们看看
原则上,您需要使用user_sticker表。所以:
SELECT *
FROM user_sticker us
然后,匹配user_to的用户表
SELECT *
FROM user_sticker us JOIN user u ON us.id_user_to = u.id_user
然后,您需要要收到的用户的名称和贴纸
SELECT us.id_sticker, u.name
FROM user_sticker us JOIN user u ON us.id_user_to = u.id_user
WHERE u.id_user = "yourwanteduser"
现在,选择第一个
SELECT TOP 1 us.id_sticker, u.name
FROM user_sticker us JOIN user u ON us.id_user_to = u.id_user
WHERE u.id_user = "yourwanteduser"
ORDER BY (SELECT COUNT(*)
FROM user_sticker us2
WHERE us2.id_user_to=u.id_user AND us2.id_sticker=us.id_sticker)
ORDER BY用于搜索向该用户发送了多少贴纸
抱歉我的英语不好!我希望这有帮助!
答案 2 :(得分:0)
select test.id_sticker, test.id_user_to, name from
(select s.id_sticker, s.id_user_to
from user_sticker s, user u
group by id_sticker, id_user_to
order by count(*) desc
limit 1)
as test, user
where test.id_user_to=user.id_user
请参阅sql fiddle链接:http://sqlfiddle.com/#!2/e02ca/6/0