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

该博客讨论了一个MySQL查询问题,涉及如何从主表中选取那些在子表中拥有特定组合选项值的记录。作者尝试通过JOIN操作结合IN和AND条件,但未能得到预期结果。解决方案提供了使用两个JOIN和LEFT OUTER JOIN的查询方法,以确保主表记录同时匹配子表中的两个不同条件。
摘要由CSDN通过智能技术生成

I was writing a mysql filter query which has a primary table and another table which holds multiple records against each record of primary table (I will call this table child).

Am trying to write a query which fetches record of primary table based on its values on child table. If the child table condition is one then I will be able to do it simply by joining, but I have 2 conditions which falls on same field.

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

My query has to return unique master records when the optionvalue matches only both 2 different conditions match on second table.

I wrote query with IN...

select * from table1

left join table2 on table1.id=table2.masterid

where table2.optionvalue IN(2,7) group by table1.id;

This gets me all 3 records because IN is basically checking 'OR', but in my case I should not get 3rd master record because it has values 2,6 (there is no 7). If I write query with 'AND' then am not getting any records...

select * from table1

left join table2 on table1.id=table2.masterid

where table2.optionvalue = 2 and table2.optionvalue = 7;

This will not return records as the and will fail as am checking different values on same column. I wanted to write a query which fetches master records which has child records with field optionvalues holds both 2 and 7 on different records.

Any help would be much appreciated.

解决方案

Indeed, as AsConfused hinted, you need to two joins to TABLE2 using aliases

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值