简体   繁体   English

从MySQL中的一个表合并两个选择查询

[英]Combine two select queries from one table in MySQL

I have mysql table with structure like 我有结构像mysql表

id | first_id | second_id
 1 |        1 |         2
 2 |        1 |         4
 3 |        1 |         9
 4 |        4 |         6
 5 |        5 |         9
 6 |        9 |        10

I want to get list of ids that are in one pair with x : 我想获取与x成对的ID列表:

Each pair of ids represents relationship between 2 objects. 每对ID代表2个对象之间的关系。 So I want to get all ids of objects that have relations with object x . 因此,我想获取与对象x有关系的所有对象ID。

SELECT first_id 
  FROM Table 
 where second_id = x 
  JOIN SELECT second_id 
         FROM Table 
        where first_id = x

This query return syntax error for some reason - what am I doing wrong? 由于某种原因,该查询返回语法错误-我在做什么错?

The below query will check the x value with both second_id as well as first_id and get the first_id and second_id respectively. 下面的查询将同时检查second_id和first_id的x值,并分别获取first_id和second_id。

SELECT first_id as Id
FROM Table 
WHERE second_id = x 
UNION ALL 
SELECT second_id 
FROM Table 
WHERE first_id = x

It should be something like: 应该是这样的:

SELECT 
    a.`id` as `id`,
    a.`first_id` as `first_id`,
    b.`first_id` as `related_id`
FROM Table a
JOIN Table b
ON a.`first_id` = b.`second_id`
WHERE a.`first_id` = x

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

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