Mysql 如何选择一篇文章及其所有相关文章?

Mysql 如何选择一篇文章及其所有相关文章?,mysql,sql,Mysql,Sql,我有一个这样的问答网站。我有一张这样的桌子: // qanda +----+----------+----------------------+---------+------+ | id | title | content | related | type | +----+----------+----------------------+---------+------+ | 1 | a title | a content | NUL

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

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

以下是我当前的查询:

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
,我需要选择这三行。我该怎么做呢?

下面的查询应该可以工作。查询分为4个部分,这些部分联合在一起。每个查询的说明:

  • 如果
    :id
    是问题,则返回问题
  • 如果
    :id
    是问题,则返回答案
  • 如果
    :id
    是答案,则返回问题
  • 如果
    :id
    是答案,则返回答案
  • 查询:

    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 
    

    将您的模式划分为问答表,然后对父问题的每个答案都有一个外键约束,这会更有意义。这种当前的设计是一种disaster@Alex我将改变我的数据库设计(创建两个独立的问题和答案表),就像你在我的网站的下一个版本中所说的那样。。目前我需要解决我面临的问题。您当前存储了多少数据,如果您现在可以迁移到新的数据库设计,我强烈推荐。当您使用当前的设计进行扩展时,您将遇到一些严重的性能瓶颈,@juergend My query在
    :id=2
    时只返回一行。只有一个问题,为什么我的问题赢得了两张反对票?有什么不对吗?有根据的猜测:我怀疑有些人被否决了,因为他们根本不同意你的db设计。就我个人而言,我不认为这是否决投票的正当理由。向下投票应该是针对(当你悬停在向下投票图像上时,它会说)缺乏努力、没有用处或不清楚的问题。虽然不是每个人都同意你的想法,但我认为你已经清楚地解释了自己,特别是当我与90%的SQL问题进行比较时。我同意@sstan comment,尽管我不同意你的数据库设计,但我确实对你的帖子投了更高的票,因为你显然花了很多时间来创建它。这不是低质量的,所以我不相信它值得被否决!