我有一个名为 related_post 的MySQL表,如下所示:
+----+--------+--------+
| id | post_1 | post_2 |
+----+--------+--------+
| 1 | 25 | 26 |
| 2 | 25 | 27 |
| 3 | 25 | 28 |
| 4 | 26 | 27 |
| 5 | 26 | 28 |
| 6 | 27 | 28 |
| … | … | … |
+----+--------+--------+
我需要检索给定帖子ID的所有相关帖子。
如果我提供'27',我希望它以“25”,“26”和“28”作为值返回单个列。
现在,我需要将其拆分为2个查询:
SELECT post_1 FROM related_post where post_2 = 27;
SELECT post_2 FROM related_post where post_1 = 27;
我想知道是否可以只执行一个查询来完成相同的结果。
答案 0 :(得分:3)
尝试UNION
:
SELECT post_1 AS post FROM related_post where post_2 = 27
UNION
SELECT post_2 FROM related_post where post_1 = 27
UNION
也会删除重复项;如果您不想这样,请使用UNION ALL
答案 1 :(得分:3)
您可以使用CASE语句在一个查询中执行此操作
SELECT CASE WHEN post_2 = 27 THEN post_1 ELSE post_2 END as post
FROM related_post
WHERE post_2 = 27 OR post_1 = 27;