gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:06:04 25 4
gpt4 key购买 nike

我想知道这里是否有人可以帮助解决我遇到的问题。我正在尝试使用子查询将 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

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

谢谢

最佳答案

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
)

关于mysql - 使用子查询组合 2 个 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5807481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com