Example tables would be:
object
id | name |
---|---|
0 | obj0 |
1 | obj1 |
2 | obj2 |
attr
id | description |
---|---|
0 | attr0 |
1 | attr1 |
2 | attr2 |
link
o_id | a_id |
---|---|
0 | 0 |
0 | 1 |
0 | 2 |
1 | 1 |
I now want to generate a SQL that returns only objects having at least a given set of attributes. I tried JOIN, but that returns either nothing or too much.
My attempt to get an object with attributes "attr0" and "attr1" (which should match only obj0 in this case):
SELECT o.name
FROM link l
INNER JOIN object o ON o.id = l.o_id
INNER JOIN attr a ON a.id = l.a_id
WHERE a.description = 'attr0'
AND a.description = 'attr1'
This returns nothing because after the JOIN those are unique lines. With OR instead of AND, it returns both obj0 and obj1.
The result I want to see would be only obj0, because it’s the only one having attr0 and attr1.
Example (wanted) result:
|o.id|o.name|
|:–:|:—-:|
| 0| obj0|
Is there a way to do this inside SQL, instead of having to filter in code later? I feel doing it via SQL and thus in the database would make my code much faster.
4
Answers
A simple approach would be to limit the select on
o.id = 0
Your query is not going to work due to the "AND". There is no register that satisfies both conditions. Try to change it for an "OR"
Or better, you can use IN
Then you can filter for the object you want:
Think you need something like this – a simple aggregation grouped by object and filtered with Having clause:
See the fiddle here.
Your example is messed up, as you look for ‘attr1’ and ‘attr2’ and want obj1 returned which only has ‘attr1’.
However, you want to select an object, so select from the object table. You want to limit the result, so use a where clause. There is no need to join. Use
EXISTS
orIN
to check whether the desired attributes exist for the object:The same with
EXISTS
: