drtpbx3606 2014-06-28 16:57
浏览 64
已采纳

基于各个COUNT(*)值的查询

I have two tables ('posts' and 'votes') which allows users to vote thumbs-up (where rating = 1 in 'votes') or thumbs-down (where rating = 0 in 'votes') on posts.

I'm joining the two tables in a query and am trying to filter the results so that a row only shows if it has 2+ positive (rating = 1) ratings AND 2+ negative (rating = 0) ratings from the 'votes' table ('post_id' and 'rating' columns).

This is what I got, but it doesn't work as intended, since it brings back results which also have only 1 positive and 1 negative vote -- although you can't see this due to the conglomeration of votes for each post -- which isn't what I want (the 'HAVING' line isn't working as intended):

SELECT *, COUNT(*)
FROM posts p
JOIN votes v ON p.id = v.post_id
WHERE rating = 1 OR rating = 0
GROUP BY p.id 
HAVING COUNT(rating = 1) > 1 AND COUNT(rating = 0) > 1

+----+---------+----------+----------+
| id | post_id | rating   | COUNT(*) |
+----+---------+----------+----------+
|  4 |       4 |        0 |        2 |
|  7 |       7 |        0 |        2 |
|  9 |       9 |        0 |        2 |
| 83 |      83 |        1 |        2 |
+----+---------+----------+----------+
  • 写回答

1条回答 默认 最新

  • douzao1119 2014-06-28 16:59
    关注

    I think you want this having clause:

    SELECT p.*, COUNT(*)
    FROM posts p JOIN
         votes v
         ON p.id = v.post_id
    WHERE rating IN (1, 0)
    GROUP BY p.id 
    HAVING ABS(SUM(rating = 1) - SUM(rating = 0)) > 1;
    

    EDIT:

    The above is doing the right thing. Here is a SQL Fiddle showing the results.

    EDIT II:

    I might have misinterpreted the question. I understood the question to be a net positive of two votes or a net negative of two votes. You seem to want just at least two votes either way. That having clause is:

    HAVING SUM(rating = 1) > 1 or SUM(rating = 0) > 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制