【发布时间】:2013-06-30 01:34:16
【问题描述】:
上一个问题:SQL query of relationship between two items from the same table。
我希望能够将同一个表中的项目与连接表相关联。与上面的问题类似,但我想知道是否可以从相互链接的表中查询所有项目。
entries
id
name
similars (join table connecting two entries)
one_id
two_id
car - train
\
bicycle - shopping cart
是否可以查询链接到“自行车”的所有项目并获得如下结果:
Entry | Similar_to
---------------------
Bicycle | Shopping cart
Bicycle | Car
Bicycle | Train
更新:
似乎我需要递归来执行此操作,所以我从 mysql 转移到了 postgresql。 目前想知道如何使用连接表完成递归。这是一个在链表上以一种方式工作的表设置和查询:
CREATE TABLE entries
(
id serial primary key,
name varchar(20)
);
INSERT INTO entries
(name)
VALUES
('Car'),
('Train'),
('Bicycle'),
('Shopping cart'),
('Node'),
('Skis'),
('Skates');
CREATE TABLE similars
(
one_id int,
two_id int
);
INSERT INTO similars
(one_id, two_id)
VALUES
(1, 2),
(1, 3),
(3, 4),
(6, 7);
查询,现在有额外的 postgresql
WITH RECURSIVE temp AS
(
SELECT * FROM entries WHERE name = 'Bicycle'
UNION ALL
SELECT e.*
FROM entries AS e
LEFT JOIN similars AS s
ON e.id = s.two_id
JOIN temp l
ON s.one_id = l.id
)
SELECT * FROM temp;
这样我得到的结果会很好,但仍然需要弄清楚如何获得其余的结果。
ID NAME
3 Bicycle
4 Shopping cart
New SQLfiddle。如果有人知道如何在链表上获得双向结果,那就太好了。
【问题讨论】:
-
我可能不够聪明,但我不知道你在问什么。你能提供一些示例输出吗?
-
为我要查找的内容添加了一些输出
-
好的,我现在明白了.. 您希望在所有情况下都将自行车排在第一位。无论它是在相似表的第 1 位还是第 2 位。
-
我想你想要的是回避。在 SQL Server 中,这将通过递归 CTE 完成,但我不知道我的 sql 是否有这些。您可能会遇到某种类型的光标。
-
mysql 没有。它必须在存储过程中完成。
标签: mysql sql postgresql