I have mysql table with structure like
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 :
Each pair of ids represents relationship between 2 objects. So I want to get all ids of objects that have relations with object x .
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.