我有以下PostgreSQL语句:
SELECT answer, answermark,answerid, answer.questionid, quizid
FROM answer
LEFT JOIN questions
ON answermark = answer.questionid
WHERE quizid = 1
ORDER BY answermark
然而,我得到的结果与我的3行重复 寻找。如何更改查询以消除重复项。
答案 0 :(得分:1)
在select语句中使用distinct可以删除重复项
试试这个: -
SELECT distinct answer, answermark,answerid, answer.questionid, quizid FROM answer
LEFT JOIN questions ON answermark = answer.questionid WHERE quizid =1
ORDER BY answermark
答案 1 :(得分:0)
您需要使用限定的列名来编写查询。每个列引用都应包含表名。这是一个好习惯;它会阻止您所看到的意外结果。
根据列名称,我认为您的查询是:
SELECT a.answer, a.answermark, a.answerid, a.questionid, q.quizid
FROM answer LEFT JOIN
questions q
ON a.answermark = a.questionid
---------^ I am guessing `answermark` comes from `answer`, not `questions`.
WHERE q.quizid = 1
ORDER BY a.answermark;
我不知道为什么名为answermark
的列会与名为questionid
的列进行比较,而不管表的来源如何。如果这是一个有效的比较,那么您的数据库的命名约定非常差。
我怀疑你想要这样的东西:
SELECT a.answer, a.answermark, a.answerid, a.questionid, q.quizid
FROM answer LEFT JOIN
questions q
ON q.questionid = a.questionid
WHERE q.quizid = 1
ORDER BY a.answermark;