gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:26:57 25 4
gpt4 key购买 nike

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

最佳答案

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

  1. 如果 :id 是一个问题则返回问题
  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

关于mysql - 如何选择帖子及其所有相关帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com