2016-08-14 91 views
1

我有一个像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或答案的编号)

这里是我当前的查询:

SELECT * FROM qanda WHERE id = :id OR related = :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。我怎样才能做到这一点?

+0

将您的模式划分为问题和答案表格,然后对每个父问题答案都有一个外键约束会更有意义。这个当前的设计是一个灾难配方 – Alex

+0

@Alex我会改变我的数据库设计*(为问题和答案创建两个分开的表)*就像你在我的网站的下一个版本中说的..目前我需要解决的问题我'米面临着。 –

+0

您目前存储多少数据,如果您现在可以迁移到新的数据库设计,我会强烈推荐它。当你用这个当前的设计进行缩放时,你会碰到一些严重的性能瓶颈, – Alex

回答

1

以下查询应该可以工作。该查询分为4个部分组合在一起。每个查询的描述:如果:id

  1. 返回问题是一个问题
  2. 返回答案,如果:id是一个问题
  3. 返回的问题,如果:id一个答案
  4. 返回答案,如果: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 
+0

只有一个问题,为什么我的问题已经获得了两个downvotes?它出什么问题了? –

+2

受过教育的猜测:我怀疑有些人因为他们根本不同意你的数据库设计而被低估。就我个人而言,我认为这不是一个合理的理由。 Downvotes应该是(因为它表示当你将鼠标悬停在downvote图像上时)显示缺乏努力的问题,没有用处或不清楚。虽然不是每个人都可能同意你想要做的事情,但我认为你清楚地解释了自己,特别是当我比较SO上提出的90%的SQL问题时。 – sstan

+2

我同意@sstan的评论,尽管我不同意你的数据库设计,因为你显然投入了创建它的时间,所以我实际上赞成了你的文章。这不是低质量的,所以我不相信它值得投票! – Alex

相关问题