Ich habe diese Strukturtabelle:Wie kann ich alle zugehörigen Posts auswählen?
// qanda
+----+----------------------------------------+---------+-----------+------+
| Id | body | related | user_id | free |
+----+----------------------------------------+---------+-----------+------+
| 1 | content of question1 | null | 2 | null |
| 2 | content of first answer for question1 | 1 | 2 | null |
| 3 | content of question2 | null | 6 | 300 |
| 4 | content of second answer for question1 | 1 | 4 | null |
| 5 | content of first answer for question2 | 3 | 2 | null |
| 6 | content of question3 | NULL | 8 | null |
| 7 | content of first answer for question3 | 6 | 4 | null |
| 8 | content of second answer for question3 | 6 | 2 | null |
+----+----------------------------------------+---------+-----------+------+
/* related column: it is NULL for questions, and the id of its own question for answers.
free column: Actually that's just for questions. NULL means it is a free question
and any number else means it isn't. (answers always are NULL) */
Ich brauche alle Antworten eines Benutzers auszuwählen, die auf eine freie Frage gehört. Zum Beispiel möchte ich alle Antworten dieses Benutzers auswählen: $user = 2
. So wird dies erwartet Ergebnis:
+----+----------------------------------------+---------+-----------+------+
| Id | body | related | user_id | free |
+----+----------------------------------------+---------+-----------+------+
| 2 | content of first answer for question1 | 1 | 2 | null |
| 8 | content of second answer for question3 | 6 | 2 | null |
+----+----------------------------------------+---------+-----------+------+
Wie kann ich das tun?
SELECT a.*
FROM qanda q
JOIN qanda a
ON q.id = a.related
WHERE related IS NOT NULL -- this specifics answers
AND user_id = 2
AND ...
Was ist los mit 'UND a.free IST NULL' oder' UND q.free IS NULL'? –
@KenWhite Ok Ich habe es getestet und ja [es funktioniert] (http://sqlfiddle.com/#!9/81151/3). Vielen Dank. –