Cars:
x
id name
1 Mercedes
2 Audi
CarAttributes:
id car_id attribute
1 1 fast
2 1 modern
3 1 fancy
4 1 green
5 2 fast
6 2 quiet
7 2 blue
8 2 old
How would the sql query look if the returns depend on the attributes of the car like following:
[fast OR modern] AND [fancy OR old] = would return both cars
[fast OR modern] AND [old OR blue] = would only return the audi car
Advertisement
Answer
You can use aggregation with a having
clause:
select car_id
from carattributes
group by car_id
having sum( attribute in ('fast', 'modern')) > 0 and
sum( attribute in ('fancy', old')) > 0