dongnai6973 2009-12-21 06:40
浏览 74
已采纳

MySQL查询在上周获得前十名收入者?

I'm trying to write a query that returns the user ID's of the top 10 users who gained the most points in the last 7 days on my web app.

I have three tables that, together, have the info I need.

  1. votingapi_votes table. It has a record for every up/down vote on a comment or node.
  2. node table. It can associate a node ID with a user ID so you can figure out who posted the story getting the votes.
  3. comments table, which does the same for comments.

I believe I need to write a query that selects every vote on a comment or node from the last week from the votingapi_vote table.

Here's the structure of that table:

  • vote_id
  • content_type
  • content_id
  • value
  • value_type
  • tag
  • uid
  • timestamp

So I'd SELECT rows of content_type "node" or "comment" with a Unix timestamp greater than time() - 684000.

Then it needs to

  1. group these votes by "content_id".

  2. Look up the respective "user_id" values for each content_id in the "node" and "comments" tables so we know who made the nodes and comments.

  3. Calculate how many points total each user_id gained from his nodes and comments.

  4. Sort these user_id's in reverse order and limits it to displaying only the first 10.

Phew. That seems like what I need to do. Now what does that actual query look like?

  • 写回答

3条回答 默认 最新

  • dongsui3297 2009-12-21 07:38
    关注

    Posting based on OMG Ponies' answer

    SELECT x.user_id, SUM(x.total_votes)
        FROM (
            SELECT n.user_id, SUM(vav.value) AS total_votes
                FROM NODE n
                JOIN VOTINGAPI_VOTES vav 
                    ON vav.content_id = n.nid
                    AND vav.content_type = 'node'
                WHERE vav.timestamp > NOW() - 684000
                GROUP BY n.user_id
            UNION
            SELECT c.user_id, SUM(vav.value) AS total_votes
                FROM COMMENTS c
                JOIN VOTINGAPI_VOTES vav 
                    ON vav.content_id = c.cid
                    AND vav.content_type = 'comment' 
                WHERE vav.timestamp > NOW() - 684000
                GROUP BY c.user_id
        ) x
        GROUP BY 
            x.user_id
        ORDER BY 
            x.total_votes DESC
        LIMIT 10
    

    The problem with the earlier code is that it returns 2 rows per user, 1 for comment, 1 for node. This code will do another SUM to aggregate it to just 1 number per user.

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

报告相同问题?

悬赏问题

  • ¥15 BV260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序