我有像
这样的结构的mysql表id | first_id | second_id
1 | 1 | 2
2 | 1 | 4
3 | 1 | 9
4 | 4 | 6
5 | 5 | 9
6 | 9 | 10
我想获得一对 x 中的ID列表:
每对id表示2个对象之间的关系。所以我想获得与对象 x 有关系的所有对象ID。
SELECT first_id
FROM Table
where second_id = x
JOIN SELECT second_id
FROM Table
where first_id = x
此查询因某种原因返回语法错误 - 我做错了什么?
答案 0 :(得分:1)
以下查询将使用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
答案 1 :(得分:0)
应该是这样的:
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