首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >高级Mysql查询,如果两个条件在不同的子记录行上匹配,则获得主记录

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

Stack Overflow用户
提问于 2015-06-20 21:23:33
回答 4查看 1.4K关注 0票数 3

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

我试图编写一个查询,该查询根据子表上的主表值获取主表的记录。如果子表条件是一个,那么我可以通过加入简单地完成它,但是我有两个条件落在相同的字段上。

代码语言:javascript
复制
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写了查询..。

代码语言:javascript
复制
select * from table1 
left join table2 on table1.id=table2.masterid 
where table2.optionvalue IN(2,7) group by table1.id;

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

代码语言:javascript
复制
select * from table1 
left join table2 on table1.id=table2.masterid 
where table2.optionvalue = 2 and table2.optionvalue = 7;

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

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-06-20 21:30:11

实际上,正如AsConfused所暗示的,您需要使用别名两个连接到TABLE2。

-- both of these are tested

代码语言:javascript
复制
-- 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
票数 5
EN

Stack Overflow用户

发布于 2015-06-20 21:38:24

您可以尝试这样的方法(没有性能保证,并且假设您只需要精确的匹配):

代码语言:javascript
复制
select table1.* from table1 join
(select masterid, group_concat(optionvalue order by optionvalue) as opt from table2 
group by masterid) table2_group on table1.id=table2_group.masterid
where table2_group.opt='2,7';

http://sqlfiddle.com/#!9/673094/9

票数 2
EN

Stack Overflow用户

发布于 2015-06-20 22:26:00

选择*从t1 where id in (从t2 where选择masterid (t2.SUMERID in (从t2 where optionvalue=2选择masterid ))和( t2 masterid in (从t2 where optionvalue=7选择masterid)

老派:-)查询花了0.0009秒。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30959041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档