There are tables: groups, targets and join table groups_targets.
Groups have targets, for example:
- Group #1 has a gender target, an age target, and a city target
- Group #2 has a gender target
- Group #3 has a city and gender target.
- Group #4 has an age and city target.
My request does not return anything
SELECT DISTINCT groups.*
FROM groups
INNER JOIN groups_targets ON groups_targets.group_id = groups.id
INNER JOIN targets ON targets.id = groups_targets.target_id
WHERE groups.user_id = 1
AND (targets.name = 'age' AND targets.name = 'gender')
How to find groups that have both gender and age, only group #1.
3
Answers
(targets.name = 'age' AND targets.name = 'gender')
will always return false, targets.name can’t have two values at the same time, UseOR
instead ofAND
:If both targets should be there, we can use
GROUP BY
andHAVING
clauses alongside theCASE
clause to specifically choose groups containing both targets :To get all groups having target
age
use the join query with the proper filter ontarget name
Use similar query for the target
gender
To get groups with both targets use
intersect
of the previous queries, i.e.group_id
‘s returned in both queriesTo find groups that have both gender and age targets, you should use a different approach, such as using the EXISTS clause with subqueries.
The query should give you the desired result, which is finding groups that have both gender and age targets.
Hope this helps.