douzhi3105 2011-06-06 10:53
浏览 46
已采纳

帮助棘手的MySQL查询

I'd appreciate your help on this please :

I've got a table which logs when an user (id_user) where at an event (meeting, concert..) (id_event) and his score for this event (long story). Here is my table:

CREATE TABLE `Leaderboards` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `id_event` mediumint(8) NOT NULL,
  `user_id` mediumint(9) NOT NULL,
  `score` smallint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Now, I'd like to suggest to an user all the users which have been to at least one event in common, and sort it by users which have been to a lot of events in common.

I might have an idea to do it in php after a row request, but is there a smarter way to do it directly through MySQL?

Thank you for your answers!

  • 写回答

4条回答 默认 最新

  • doujiang3997 2011-06-06 11:10
    关注

    I think I might have an answer for you

    SELECT leader1.user_id, leader2.user_id, COUNT(leader1.id) AS num
    FROM       Leaderboards AS leader1
    INNER JOIN Leaderboards AS leader2 ON (
        leader1.id_event = leader2.id_event AND
        leader1.user_id != leader2.user_id
    )
    GROUP BY leader1.user_id, leader2.user_id
    ORDER BY num DESC
    

    This will select the ids of the users who at least one event in common, as well as the number of events. Finally it will order by the number of events in common (num) descending. If you would like to do it for a specific user, add in a where clause such as below

    WHERE leader1.user_id = :user_id
    

    I also believe this query if pretty efficient as well. Let me know if this is not quite what you need and I will see if I can make adjustments.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。