0

我有两张桌子: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
4

3 回答 3

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 */

诀窍是查询所有questionsleft join. questions_lookup通过将 user_id 添加到 join 条件,您将省略其他用户的记录,同时仍然返回当前用户没有记录的问题。如果移至ql.user_id = 5where 子句,查询将不再有效,因为它会有效地将左连接变为内连接。

[编辑]

我看到你已经添加了你的查询。那里有两个错误。右连接应该是左连接,因为你总是希望左边有记录(问题),右边有可选记录(查找)。此外,条件不应出现在 where 子句中。

于 2013-01-29T21:06:20.407 回答
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表示用户已回答。

于 2013-01-29T21:09:55.467 回答
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
于 2013-01-29T21:19:19.453 回答