0

私は2つのテーブルを持っています: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)

date_created順に質問テーブルからすべての質問を取得し、ユーザーがそれに回答したかどうかを表示するphpページが必要です。結合しようとすると、他のユーザーの回答が表示されるため、質問が重複して表示されることになります。

したがって、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

どうですか :

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 に答える