【问题标题】:Tally votes using SQL and JOIN (is this possible?)使用 SQL 和 JOIN 进行统计投票(这可能吗?)
【发布时间】:2011-12-20 09:40:51
【问题描述】:

我的问题是similar to this one,我已经尝试过解决方案,但它并不完全适合我的方案。

我有 2 个表格:投票和帖子。这是一个基本草图:

`posts`
----+------------------------------------------------------------------------+
| ID | post_title                                                            |
+----+-----------------------------------------------------------------------+
|  1 | Hello world.                                                          |
|  2 | This is a post!                                                       |
|  3 | What is the meaning of life?                                          |
|  4 | Looking for a good time?                                              |
+----+-----------------------------------------------------------------------

`votes`
+----+---------+
| ID | post_id | 
+----+---------+
|  1 |     1   |  
|  2 |     1   | 
|  3 |     1   |  
|  4 |     3   | 
|  5 |     3   |  
|  6 |     4   |  
+----+---------+

问题

我想知道每个帖子获得了多少票,并显示它们,使得票最高的帖子位于顶部。

     Post ID   Vote Count
   +---------+-----------+
   | 1       | 3         |
   | 3       | 2         |
   | 4       | 1         |
   | 2       | 0         |

实现此目标的 SQL 查询是什么样的?

【问题讨论】:

    标签: mysql sql database posts


    【解决方案1】:
    select post_id, count(*)
    from votes
    group by post_id
    order by count(*) desc
    

    编辑:

    select v.post_id, count(*)
    from votes v INNER JOIN posts p ON v.post_id = p.id
    group by v.post_id
    order by count(*) desc
    

    【讨论】:

    • 效果很好,谢谢! (显示 post_title 而不是 id 会更难吗?)
    • @Ankur 只是加入帖子并将 post_title 添加到 SELECT 和 GROUP BY 子句
    【解决方案2】:
    SELECT post_id, COUNT(*) AS tally
      FROM votes
     GROUP 
        BY post_id
    UNION
    SELECT ID AS post_id, 0 AS tally
      FROM posts
     WHERE ID NOT IN (SELECT post_id FROM votes);
    

    【讨论】:

      【解决方案3】:

      如果您想在不执行 UINON 的情况下包含零票数的帖子,您可以这样做

        SELECT 
               p.id, 
               SUM(CASE WHEN v.post_id IS NOT NULL THEN 1 ELSE 0 END)  AS tally
        FROM  
            posts p
            LEFT JOIN votes v
            ON v.post_id = p.id
        ORDER BY  
            SUM(CASE WHEN v.postid IS NOT NULL THEN 1 ELSE 0 END) DESC
        GROUP 
          BY p.id
      

      此处需要 SUM/CASE,因为 COUNT(NULL) = 1

      由于您的结构如此接近,这里是an example,您可以在 data.SE 上查看

      【讨论】:

        猜你喜欢
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多