的2列的我有一個VoteQuestion
表:VoteQuestion(idUser → User, idQuestion → Content, isUp)
差異查詢
和Question
表:Question(idQuestion → Content, title)
我要選擇的5個問題的最佳成績(upvotes-downvotes)。
向上投票是VoteQuestion
與isUp = TRUE
和downvote a VoteQuestion
與isUp = FALSE
。
我嘗試了以下查詢,但這不是我正在尋找的。它爲每個問題提供相同的分數。
WITH upvotes AS
(
SELECT COUNT(*) AS "a"
FROM "VoteQuestion", "Question"
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
AND "VoteQuestion"."isUp" IS TRUE
),
downvotes AS
(
SELECT COUNT(*) AS "b"
FROM "VoteQuestion", "Question"
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
AND "VoteQuestion"."isUp" IS FALSE
)
SELECT "title", "Question"."idQuestion", upvotes."a"-downvotes."b" AS total
FROM "VoteQuestion", "Question", upvotes, downvotes
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
GROUP BY "title", "Question"."idQuestion", upvotes."a", downvotes."b"
ORDER BY "total" DESC
LIMIT 5
也試過這樣:
SELECT "title", "Question"."idQuestion",
(SELECT COUNT(*)
FROM "VoteQuestion", "Question"
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
AND "VoteQuestion"."isUp" IS TRUE
) AS upvotes,
(SELECT COUNT(*)
FROM "VoteQuestion", "Question"
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
AND "VoteQuestion"."isUp" IS FALSE
) AS downvotes, upvotes-downvotes AS total
FROM "VoteQuestion", "Question"
WHERE "VoteQuestion"."idQuestion" = "Question"."idQuestion"
GROUP BY "title", "Question"."idQuestion"
ORDER BY total DESC
LIMIT 5
但它說ERROR: column "upvotes" does not exist
我怎樣才能得到來自查詢的列upvotes和downvotes的區別?
是的,試過這個,它的工作原理。順便說一句,你有一個錯字 - 'ORDER BY total DESC'。感謝您的回答,謝謝! –
'ORDER BY 3 DESC'指的是列總數,因爲它是投影中的第三列。 –
哦,一直在學習! :) –