使用一个查询获取两个结果

时间:2016-07-27 23:31:22

标签: mysql sql

我希望通过特定的用户ID以及特定网页ID的所有喜欢和喜欢获得喜欢的结果。

我的结构如下:

`pages`: (id, title)
`pages_likes`: (id, page_id, uid, status)

如果status-1,则表示不喜欢特定网页,如果它是1,则表示不喜欢。

所以,为了得到所有喜欢这是我的疑问:

SELECT COUNT(id) FROM pages_likes WHERE status = '1'

但是现在我也想知道如果用户ID 3例如喜欢

这个页面
SELECT COUNT(id) FROM pages_likes WHERE status = '1' AND uid='3'

如何在一个查询中实现这两个目标?我想在SELECT语句之后必须改变一些东西吗?

3 个答案:

答案 0 :(得分:2)

我认为这样可行:

SELECT '' user, COUNT(id) likes 
FROM pages_likes 
WHERE status = '1' 
GROUP BY 1

UNION ALL

SELECT uid user, COUNT(id) likes 
FROM pages_likes 
WHERE status = '1' AND uid='3'
GROUP BY 1

答案 1 :(得分:2)

如果要在单个查询中执行此操作,请使用条件聚合:

SELECT SUM(CASE WHEN uid = '3' THEN 1 ELSE 0 END) AS threeLikes,
       SUM(CASE WHEN uid <> '3' THEN 1 ELSE 0 END) AS otherLikes
FROM pages_likes
WHERE status = '1'

另一种选择是使用UNION,参见@bernie给出的答案

<强>更新

如果您希望页面中的不喜欢同一个查询,可以尝试:

SELECT SUM(CASE WHEN uid = '3'  AND status = '1' THEN 1 ELSE 0 END) AS threeLikes,
       SUM(CASE WHEN uid <> '3' AND status = '1' THEN 1 ELSE 0 END) AS otherLikes
       SUM(CASE WHEN uid = '3'  AND status = '0' THEN 1 ELSE 0 END) AS threeDislikes,
       SUM(CASE WHEN uid <> '3' AND status = '0' THEN 1 ELSE 0 END) AS otherDisikes
FROM pages_likes

答案 2 :(得分:1)

我会这样做:

SELECT COUNT(*) AS total_likes, SUM(uid=3) AS uid3_likes
FROM pages_likes
WHERE status=1 AND page_id=1234

重新评论:

这是一个显示总喜欢和完全不喜欢的例子。它类似于@TimBiegeleisen的答案。

SELECT SUM(status=1) AS total_likes, 
       SUM(CASE WHEN uid=3 AND status=1 THEN 1 END) AS uid3_likes
       SUM(CASE WHEN uid=3 AND status=-1 THEN 1 END) AS uid3_dislikes
FROM pages_likes
WHERE page_id=1234