多个连接到同一个表
我有这组表和数据,
CREATE TABLE item (
id INT PRIMARY KEY,
name VARCHAR
);
CREATE TABLE property (
id INT PRIMARY KEY,
name VARCHAR
);
CREATE TABLE value (
id INT PRIMARY KEY,
value VARCHAR
);
CREATE TABLE item_value (
item INT NOT NULL REFERENCES item(id),
property INT NOT NULL REFERENCES property(id),
value INT NOT NULL REFERENCES value(id)
);
INSERT INTO item (id, name) VALUES (1, 'item1'), (2, 'item2');
INSERT INTO property (id, name) VALUES (1, 'prop1'), (2, 'prop2');
INSERT INTO value (id, value) VALUES (1, 'val1'), (2, 'val2');
INSERT INTO item_value (item, property, value) VALUES (1, 1, 1), (2,2,2 );
我想获得结果集:
name value_1 value_2
---------------------------
item1 val1 <null>
item2 <null> val2
并且我使用查询:
SELECT i.name as name, v1.value as value_1, v2.value as value_2
FROM item i
LEFT JOIN item_value iv ON iv.item = i.id
LEFT JOIN value v1 ON v1.id = iv.value AND v1.id = (
SELECT v.id FROM value v
JOIN property p ON p.id = iv.property
AND p.name = 'prop1' AND v.id = v1.id AND v.id = iv.value
)
LEFT JOIN value v2 ON v2.id = iv.value AND v2.id = (
SELECT v.id FROM value v
JOIN property p ON p.id = iv.property
AND p.name = 'prop2' AND v.id = v2.id AND v.id = iv.value
)
问题是:如何避免嵌套选择?
我正在使用 Postgresql
I have this set of tables and data
CREATE TABLE item (
id INT PRIMARY KEY,
name VARCHAR
);
CREATE TABLE property (
id INT PRIMARY KEY,
name VARCHAR
);
CREATE TABLE value (
id INT PRIMARY KEY,
value VARCHAR
);
CREATE TABLE item_value (
item INT NOT NULL REFERENCES item(id),
property INT NOT NULL REFERENCES property(id),
value INT NOT NULL REFERENCES value(id)
);
INSERT INTO item (id, name) VALUES (1, 'item1'), (2, 'item2');
INSERT INTO property (id, name) VALUES (1, 'prop1'), (2, 'prop2');
INSERT INTO value (id, value) VALUES (1, 'val1'), (2, 'val2');
INSERT INTO item_value (item, property, value) VALUES (1, 1, 1), (2,2,2 );
I want to get a result set:
name value_1 value_2
---------------------------
item1 val1 <null>
item2 <null> val2
and I use the query:
SELECT i.name as name, v1.value as value_1, v2.value as value_2
FROM item i
LEFT JOIN item_value iv ON iv.item = i.id
LEFT JOIN value v1 ON v1.id = iv.value AND v1.id = (
SELECT v.id FROM value v
JOIN property p ON p.id = iv.property
AND p.name = 'prop1' AND v.id = v1.id AND v.id = iv.value
)
LEFT JOIN value v2 ON v2.id = iv.value AND v2.id = (
SELECT v.id FROM value v
JOIN property p ON p.id = iv.property
AND p.name = 'prop2' AND v.id = v2.id AND v.id = iv.value
)
The question is: How can I avoid nested selects?
I'm using Postgresql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以尝试使用
You can try with