简体   繁体   English

如何将同一表上的两个查询连接在一起?

[英]How can I join together two queries on the same table?

I have a MySQL table, called related_post that looks like this: 我有一个MySQL表,名为related_post ,看起来像这样:

+----+--------+--------+
| id | post_1 | post_2 |
+----+--------+--------+
|  1 |     25 |     26 |
|  2 |     25 |     27 |
|  3 |     25 |     28 |
|  4 |     26 |     27 |
|  5 |     26 |     28 |
|  6 |     27 |     28 |
|  … |     …  |     …  |
+----+--------+--------+

I need to retrieve all the related posts for a given post ID. 我需要检索给定帖子ID的所有相关帖子。

If I supply '27', I want it to return a single column with "25", "26", and "28" as values. 如果提供“ 27”,则希望它返回一个以“ 25”,“ 26”和“ 28”作为值的列。

Right now, I need to split it up into 2 queries: 现在,我需要将其分为2个查询:

SELECT post_1 FROM related_post where post_2 = 27;
SELECT post_2 FROM related_post where post_1 = 27;

I would like to know if it's possible to perform only one query to accomplish the same result. 我想知道是否可以仅执行一个查询来完成相同的结果。

Try UNION : 尝试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 will also remove duplicates; UNION还将删除重复项; if you do not want this then use UNION ALL 如果您不希望这样做,请使用UNION ALL

you can use a CASE statement to do this in one query 您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM