我有两个表:questions
和questions_lookup
。如果放在网站上是一个很好的问题,用户会投票。
table: questions
id
question
date_created
table: questions_lookup
id
question_id // (id linked to questions table)
user_id // (the id of the user, I store this in a session variable called $me)
show // (1 or 0, show or don't show)
我想有一个php页面,它可以从date_created排序的问题表中提取所有问题,然后显示用户是否已经回答。当我尝试进行任何连接时,我最终会出现重复的问题,因为它会提取其他用户的答案。
所以如果有10个问题。并且特定用户仅回答了3.我们仍然显示所有10个问题,但标记他们已经回答的问题。
所以我基本上想要显示如下内容:
Question 1
Question 2 (answered)
Question 3 (answered)
Question 4
Question 5
Question 6
Question 7 (answered)
Question 8
Question 9
Question 10
我试过了:
SELECT * FROM questions
RIGHT JOIN questions_lookup
ON (questions.id = questions_lookup.question_id)
WHERE questions_lookup.user_id = '$me'
ORDER BY questions.date_created DESC
答案 0 :(得分:1)
这样的事情,假设questions_lookup
中每个问题每个用户只能有一条记录。
select
q.*,
case when ql.question_id is null then
'no'
else
'yes'
end as user_has_answered
from
questions q
left join questions_lookup ql
on ql.question_id = q.id
and ql.user_id = 5 /* User id of current user */
诀窍是查询所有questions
和left join
questions_lookup
。通过将user_id添加到连接条件,您将遗漏其他用户的记录,同时仍返回没有当前用户记录的问题。如果将ql.user_id = 5
移动到where子句,查询将不再有效,因为它会有效地将左连接转换为内连接。
[编辑]
我看到你添加了你的查询。那里有两个错误。右连接应该是左连接,因为你总是希望在左边有一个记录(问题),在右边有一个可选记录(查找)。此外,条件不应该在where子句中。
答案 1 :(得分:1)
怎么样:
SELECT questions.*, max(questions_lookup.show) AS show
FROM questions
LEFT JOIN questions_lookup ON questions_lookup.question_id=questions.id
WHERE (questions_lookup.user_id='youruserid' OR questions_lookup.user_id IS NULL)
GROUP BY questions.id
ORDER BY questions.date_created ASC
然后在您的搜索结果中,show=1
表示用户已回答。
答案 2 :(得分:1)
SELECT q.*,
l.user_id,
l.show,
IF(l.question_id IS NULL,'','answered') as answered
FROM questions q LEFT JOIN
questions_lookup l ON q.id = l.question_id AND
l.user_id = 5 <-- user id goes here
ORDER BY q.date_created DESC
您可以使用计算出的answered
列,具体取决于您进一步处理所需的输出:
IF(l.question_id IS NULL,'','answered') as answered <-- 'answered' if answered, empty string if not (like in your example)
IFNULL(l.question_id,0) as answered <-- question_id (if autogenerated unsigned int will be > 0) if answered, 0-if not
或GolezTrol建议
CASE WHEN ql.question_id IS NULL THEN 'no' ELSE 'yes' END as answered <-- yes if answered and no if not