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
As you may know, it is used to join and combine data from two or more tables into one common data set. In this article, I'm going to discuss special types of joins? in which you combine the same table twice—including joining a table to itself, also known as the self join.
Multiple joins can be described as a query containing joins of the same or different types used more than once, thus giving them the ability to combine multiple tables.
You use self-join to create a result set that joins the rows with the other rows within the same table. Because you cannot refer to the same table more than one in a query, you need to use a table alias to assign the table a different name when you use self-join.
It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.
You can try with
SELECT i.name as name, v1.value as value_1, v2.value as value_2
FROM item i
INNER JOIN item_value iv ON iv.item = i.id
INNER JOIN property p ON iv.property = p.id
LEFT JOIN value v1 ON p.name = 'prop1' AND v1.id = iv.value
LEFT JOIn value v2 ON p.name = 'prop2' AND v2.id = iv.value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With