简体   繁体   English

使用三个表的内部联接编写mysql查询

[英]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. 这里的联系人表包含id,first_name,last_name,..,而标签表包含id,name。 contacts2tags table contains contactid and tagid which are same as contacts.id and tags.id respectively contacts2tags表包含的ContactID和标签识别它们分别是相同contacts.id和tags.id

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: 现在,我想要的是仅显示同时具有tagid 7和tagid 4的联系人。我尝试了如下操作:

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. 我有一个ID数组存储在php的$ tmp中,我想使用这些ID并为它们编写上面的查询。 How do I do that? 我怎么做? I am not comfortable with sql. 我对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. 但是sql对于10k记录运行非常慢。 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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM