如何选择帖子及其所有相关帖子?

时间:2016-08-14 01:27:09

标签: mysql sql

我有一个像SO这样的问答网站。我有一张这样的桌子:

// qanda
+----+----------+----------------------+---------+------+
| id |   title  |       content        | related | type |
+----+----------+----------------------+---------+------+
| 1  | a title  | a content            | NULL    | 0    |
| 2  |          | a content            | 1       | 1    |
| 3  | a title  | a content            | NULL    | 0    |
| 4  |          | a content            | 1       | 1    |
| 5  |          | a content            | 3       | 1    |
+----+----------+----------------------+---------+------+
/*  type column:     "0" means it is a question, "1" means it is a answer
    related column:  it contains the id number of its own question
*/

现在我需要根据id号码选择一个问题和所有答案。 id号码可以是问题的ID或答案的ID)

这是我当前的查询:

SELECT * FROM qanda WHERE id = :id OR related = :id

仅当:id是问题的ID时,我的查询才有效。 (我的意思是如果:id是答案的ID,它无法正常工作)

以下是预期结果:

assuming either :id = 1 or :id = 2 or :id = 4
+----+----------+----------------------+---------+------+
| id |   title  |       content        | related | type |
+----+----------+----------------------+---------+------+
| 1  | a title  | a content            | NULL    | 0    |
| 2  |          | a content            | 1       | 1    |
| 4  |          | a content            | 1       | 1    |
+----+----------+----------------------+---------+------+

正如我上面提到的,如果:id = 1:id = 2:id = 4,我需要选择这三行。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

以下查询应该有效。查询分为4个部分,它们组合在一起。每个查询的描述:

  1. 如果:id是一个问题,则返回问题
  2. 如果:id是一个问题
  3. ,则返回答案
  4. 如果:id是答案,则返回问题
  5. 如果:id是答案,则返回答案
  6. 查询:

    select q.*
      from quanda q
     where q.id = :id
       and q.type = 0
     UNION ALL
    select a.*
      from quanda a
     where a.related = :id
     UNION ALL
    select q.*
      from quanda a
      join quanda q
        on q.id = a.related
     where a.id = :id
       and a.type = 1 
     UNION ALL
    select a2.*
      from quanda a1
      join quanda a2
        on a2.related = a1.related
     where a1.id = :id
       and a1.type = 1