我有一张表Content
内容(id,contentText,contentDate,idUser→User,contentType)
和表VoteQuestion
VoteQuestion (idUser→用户,idQuestion→内容,isUp)
我想选择前30个最近的问题。
SELECT *
FROM "Content"
WHERE "type" = 'QUESTION'
ORDER BY "contentDate"
LIMIT 30
但是,我想连接到另一个包含与此问题相关的信息的列,因此我不需要再次为每个返回的问题查询数据库。
例如,我想计算每个问题的投票数,并将其全部返回到同一行。
示例:
| id | contentText | contentDate | idUser | contentType | votes |
-----------------------------------------------------------------
| 2 | 'abc' | '2013-03-25'| 192 | 'QUESTION' | 10 |
我尝试了以下查询:
WITH question AS
(SELECT *
FROM "Content"
WHERE "type" = 'QUESTION'
ORDER BY "contentDate"
LIMIT 30
)
SELECT COUNT("VoteQuestion"."idUser")
FROM "VoteQuestion", question
WHERE "idQuestion" = question."id"
GROUP BY question."id";
但这不会返回投票数= 0的问题(只返回16个问题而不是30个问题)。怎么解决?
那么,我怎样才能让两个表都成为现实?如何在查询中减去isUp
为真且isUp
为假的投票?
答案 0 :(得分:1)
您可以选择投票计数:
SELECT Content.* ,
(
SELECT COUNT(*)
FROM VoteQuestion
WHERE idQuestion = Content.id
) as votes
FROM Content
WHERE type = 'QUESTION'
ORDER BY contentDate
LIMIT 30
答案 1 :(得分:1)
您需要一个外部联接:
WITH question AS (
SELECT *
FROM "Content"
WHERE "type" = 'QUESTION'
ORDER BY "contentDate"
LIMIT 30
)
SELECT COUNT("VoteQuestion"."idUser")
FROM question
LEFT JOIN "VoteQuestion" ON "idQuestion" = question."id"
GROUP BY question."id";