如何选择所有相关帖子?

时间:2016-09-08 23:25:33

标签: mysql sql join

我有这个表结构:

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

我需要选择属于免费问题的用户的所有答案。例如,我想选择此用户的所有答案:$user = 2。所以这是预期的结果:

+----+----------------------------------------+---------+-----------+------+
| 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 |
+----+----------------------------------------+---------+-----------+------+

我该怎么做?

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 ...

2 个答案:

答案 0 :(得分:1)

-- Working Query
SELECT 
    answer.*
FROM
    qanda question
        JOIN
    qanda answer ON question.Id = answer.related
WHERE
    answer.related IS NOT NULL
        AND answer.user_id = 2
        AND question.free IS NULL;

我冒昧地在测试期间稍微更改了命名,以澄清查询。

您错过了AND question.free IS NULL

根据您之前的查询,您将获得该用户的另一条记录,因为您没有检查实际相关问题的条件是否为空。

总而言之,我会考虑另一种数据库设计,但据我所知,并不总是可行。

Working example

答案 1 :(得分:-3)

您可以使用以下查询。

SELECT * FROM qanda WHERE user_id=2 AND free="" AND related IS NOT NULL;