返回用户的最常见链接ID

时间:2013-08-14 01:46:09

标签: mysql sql

我有3张桌子。 user_sticker保存用户之间发送的所有贴纸。加载配置文件视图屏幕时,我需要显示哪个是给用户最常见的标签。

用户

  • id_user
  • 名称

贴纸

  • id_sticker
  • 名称

user_sticker

  • id_user_sticker
  • id_sticker
  • id_user_from
  • id_user_to

因此,如果user_sticker拥有此信息:

  • 1,3,254,205
  • 2,2,362,205
  • 3,2,519,205
  • 4,3,945,205
  • 5,3,199,205

(这意味着用户254,362,519,945,199向用户205发送了贴纸)。 结果必须在同一记录中返回两者用户205信息(名称)和最常见的标签ID(在本例中为#3)。

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