gpt4 book ai didi

mysql - 如果两个条件在子记录的不同行上匹配,则高级 Mysql 查询获取主记录

转载 作者:可可西里 更新时间:2023-11-01 07:58:34 24 4
gpt4 key购买 nike

我正在编写一个 mysql 过滤器查询,它有一个主表和另一个表,该表针对主表的每个记录保存多条记录(我将称这个表为子表)。

我正在尝试编写一个查询,该查询根据子表上的值获取主表的记录。如果子表条件是一个,那么我只需加入即可完成,但我有 2 个条件属于同一字段。

For ex.
table 1:
id name url
1 XXX http://www.yahoo.com
2 YYY http://www.google.com
3 ZZZ http://www.bing.com

table 2:
id masterid optionvalue
1 1 2
2 1 7
3 2 7
4 2 2
5 3 2
6 3 6

optionvalue 仅匹配第二个表上的两个不同条件时,我的查询必须返回唯一的主记录。我用 IN 写了查询...

select * from table1 
left join table2 on table1.id=table2.masterid
where table2.optionvalue IN(2,7) group by table1.id;

这让我获得了所有 3 条记录,因为 IN 基本上是在检查“或”,但在我的情况下,我不应该获得第 3 条主记录,因为它的值为 2,6(没有 7)。如果我使用“AND”编写查询,则不会获得任何记录...

select * from table1 
left join table2 on table1.id=table2.masterid
where table2.optionvalue = 2 and table2.optionvalue = 7;

这不会返回记录,因为在同一列上检查不同的值时会失败。我想编写一个查询来获取主记录,该主记录的子记录的字段 optionvalues 在不同的记录上同时包含 2 和 7。

任何帮助将不胜感激。

最佳答案

确实,正如 AsConfused 所暗示的,您需要使用别名两次连接到 TABLE2

-- 这两个都经过测试:

-- find t1 where it has 2 and 7 in t2

select t1.*
from table1 t1
join table2 ov2 on t1.id=ov2.masterid and ov2.optionValue=2
join table2 ov7 on t1.id=ov7.masterid and ov7.optionValue=7

-- find t1 where it has 2 and 7 in t2, and no others in t2

select t1.*, ovx.id
from table1 t1
join table2 ov2 on t1.id=ov2.masterid and ov2.optionValue=2
join table2 ov7 on t1.id=ov7.masterid and ov7.optionValue=7
LEFT OUTER JOIN table2 ovx on t1.id=ovx.masterid and ovx.optionValue not in (2,7)
WHERE ovx.id is null

关于mysql - 如果两个条件在子记录的不同行上匹配,则高级 Mysql 查询获取主记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959041/

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