Please help with self join inside one table by different fields. given table "Items":
Used PostgreSQL.
I need to get all the values from such table, for which factId = 'fact:170' and factId1 ='fact:171' and factId1.value ='false' and arrayIndexes are the same.
It means factId 170 & 171 have relation one-to one using the same arrayIndex.
So all the values of factId 'fact:170' are needed, for which there is related by same arrayIndex factId 'fact:171' which have value 'false'.
Here is column Item in the table, it means for each Item we have own set of values 170 and 171. Thank you.
I tryed this but I am not sure this works fine and fast:
SELECT l.value
FROM Items l
INNER JOIN Items p on p.item = l.item
INNER JOIN Items c on c.item = l.item
WHERE l.factid = 'fact:170' AND c.factid = 'fact:170'
AND p.factid = 'fact:171' AND p.value='false'
AND p.arrayindex = l.arrayindex
there are a lot of duplicates after work. Please check my query.
Your query can be:
DB fiddle
Details:
tCTE query finds uniquearrayindexvalues for all rows which fulfill the conditionwhere factid = 'urn:drug:171' and value = 'false';factid = 'urn:drug:170'. Result rows are filtered by thearrayindexvalues which we received from the previous step.