繁体   English   中英

MySQL联接查询,无法弄清楚

[英]MySQL join query, can't figure it out

我有两个表: questionsquestions_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

像这样的东西,假设有只能在每用户问题的一个记录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子句,该查询将不再起作用,因为它将有效地将您的左ql.user_id = 5

[编辑]

我看到您已添加查询。 那里有两个错误。 右连接应该是左连接,因为您总是想在左边有一个记录(问题),在右边有一个可选记录(查找)。 而且,该条件不应在where子句中。

怎么样 :

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表示用户已回答。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM