I was wondering if anybody here could help with a problem I am having. I am trying to combine 2 mysql queries into one query using sub queries. I currently have the 2 queries separatly which produce the results i want:
Here are the 2 queries:
SELECT contact_id FROM contacts
WHERE acc_id = 1 AND email LIKE "paul%"
SELECT c0.contact_id
FROM contact_tags c0 INNER JOIN contact_tags c1
on c0.contact_id = c1.contact_id INNER JOIN contact_tags c2
on c1.contact_id = c2.contact_id where c0.tag_id = 1
AND c1.tag_id = 2 AND c2.tag_id = 3
Here is some example data from the tables:
Contacts:
contact_id acc_id email
54 1 paul@test.com
Tags:
id contact_id tag_id
1 54 1
2 54 2
3 54 3
4 50 1
5 50 2
Both queries when run independently produce this result which is correct:
contact_id
54
However I am trying to nest one query inside the other to produce the same result from a single query:
Here is what I have tried:
SELECT c0.contact_id
FROM
(
SELECT contact_id
FROM contacts
WHERE acc_id = 1 AND email LIKE "paul%"
) AS c0
LEFT JOIN contact_tags AS c1
ON c1.contact_id = c0.contact_id
AND (
SELECT c0.contact_id FROM contact_tags c0
INNER JOIN contact_tags c1
on c0.contact_id = c1.contact_id
INNER JOIN contact_tags c2 on c1.contact_id = c2.contact_id
where c0.tag_id = 1 AND c1.tag_id = 2 AND c2.tag_id = 3
)
WHERE c1.id IS NOT NULL
However I know this is not right as i want to return just the single unique contact id which matches all conditions as above:
contact_id
54
54
54
54
If anyone could help me out with this it would be much appreciated.
Thanks
Or: