使用子查询组合2个mysql查询

时间:2011-04-27 16:35:20

标签: mysql subquery

我想知道这里是否有人能解决我遇到的问题。我试图使用子查询将2个mysql查询组合成一个查询。我目前有2个查询分开产生我想要的结果:

以下是2个查询:

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

以下是表中的一些示例数据:

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

独立运行时的两个查询都会产生正确的结果:

contact_id
    54

但是我试图将一个查询嵌套在另一个查询中,以便从单个查询生成相同的结果:

以下是我的尝试:

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

但是我知道这不对,因为我想只返回符合上述所有条件的唯一联系人ID:

contact_id
   54
   54
   54
   54

如果有人能帮我解决这个问题,我将不胜感激。

由于

2 个答案:

答案 0 :(得分:2)

Select contact_id
From contacts
Where acc_id = 1 And email Like 'paul%'
    And contact_id In   (
                            Select Tags1.contact_id
                            From contact_tags As Tags1
                            Where Tags1.tag_id In(1,2,3)
                            Group By Tags1.contact_id
                            Having Count( Distinct Tags1.tag_id ) = 3
                            )

或者:

Select contact_id
From contacts
Where contact_id In (
                        Select C1.contact_id
                        From contact_tags As Tags1
                            Join contacts As C1
                                On C1.contact_id = Tags1.contact_id
                        Where Tags1.tag_id In(1,2,3)
                            And C1.acc_id = 1
                            And C1.email Like 'paul%'
                        Group By C1.contact_id
                        Having Count( Distinct Tags1.tag_id ) = 3
                        )

答案 1 :(得分:1)

要让查询返回将从第一个第二个查询返回的所有联系人,请使用以下命令:

(假设第一个不返回重复contact_id s)

SELECT contact_id
FROM contacts 
WHERE acc_id = 1
  AND email LIKE "paul%"

  AND contact_id IN

  ( 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
  )