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

use*_*765 3 mysql sql database

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

我试图编写一个查询,根据子表上的值来获取主表的记录.如果子表条件为1,那么我只需加入即可完成,但我有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
Run Code Online (Sandbox Code Playgroud)

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

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

这得到了我所有的3条记录,因为IN基本上是在检查'OR',但在我的情况下,我不应该获得第3主记录,因为它的值为2,6(没有7).如果我用'AND'写查询,那么我没有得到任何记录......

select * from table1 
left join table2 on table1.id=table2.masterid 
where table2.optionvalue = 2 and table2.optionvalue = 7;
Run Code Online (Sandbox Code Playgroud)

这不会返回记录,因为我会检查同一列上的不同值.我想编写一个查询,该查询获取具有子记录的主记录,其中字段optionvalues在不同记录上保存2和7.

任何帮助将非常感激.

Sta*_*tan 5

实际上,正如AsConfused暗示的那样,你需要使用别名将两个连接到TABLE2

- both of these are tested:

-- 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
Run Code Online (Sandbox Code Playgroud)