Search code examples
phpmysqlinner-joinaliases

write mysql query using inner joins for three tables


I have the following query which works perfectly:

SELECT * 
FROM contacts 
WHERE id in (

             SELECT DISTINCT contacts.id 
               FROM contacts 
             INNER JOIN contacts2tags 
                ON contacts.id = contacts2tags.contactid 
            WHERE tagid in(7,4)
                 )  

Here contacts table contains id, first_name, last_name, ..and tags table contains id, name. contacts2tags table contains contactid and tagid which are same as contacts.id and tags.id respectively

Now, what I want is, to display only the contacts which have both a tagid 7 and a tagid 4. I tried something like this:

SELECT * 
FROM contacts
WHERE id IN
    (
     SELECT CT1.contactid 
 FROM
tags T1, contacts2tags CT1, tags T2, contacts2tags CT2
WHERE CT1.contactid = CT2.contactid
 AND CT1.tagid = T1.id
 AND CT2.tagid = T2.id
 AND (T1.id = 7 AND T2.id = 4)

and it works too. My problem is, I want to convert the above second query to one using inner joins. I have an array of ids stored in $tmp in php I want to use those ids and write the above query for them. How do I do that? I am not comfortable with sql. Might be its a very simple thing to ask. Thanks in advance

EDIT: The answer below solved the problem. But the sql runs very slow for 10k records. Any suggestions to optimise it? Pasting the updated query as given in the answer.

    SELECT c.id 
     FROM contacts c
    inner join contacts2tags t on c.id = t.contactid 
    where t.tagid in (7,4)
    group by c.id
    having count(distinct t.tagid) = 2

Solution

  • This should work

    SELECT c.id 
    FROM contacts c
    inner join contacts2tags t on c.id = t.contactid 
    where t.tagid in (7,4)
    group by c.id
    having count(distinct t.tagid) = 2