簡體   English   中英

高級Mysql查詢,如果兩個條件匹配不同的子記錄行,則獲取主記錄

[英]Advanced Mysql Query to get master record if two conditions matches on different rows of child records

我正在編寫一個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

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基本上是在檢查'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;

這不會返回記錄,因為我會檢查同一列上的不同值。 我想寫這取其中有子記錄與現場主記錄的查詢optionvalues上不同的記錄同時擁有2和7。

任何幫助將非常感激。

實際上,正如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

您可以嘗試這樣的事情(沒有性能保證,並假設您只想要完全匹配):

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

select * from t1 where id in(select tid from t2 where(t2.masterid in(select selectid from t2 where optionvalue = 2))和(t2.masterid in(select selectid from t2 where optionvalue = 7)))

老學校:-)查詢耗時0.0009秒。

這也可以在沒有使用相關的存在子查詢的連接的情況下完成。 這可能更有效率。

select *
  from table1 
 WHERE EXISTS (SELECT 1 FROM table2 WHERE table1.id=table2.masterid and optionvalue = 2)
   AND EXISTS (SELECT 1 FROM table2 WHERE table1.id=table2.masterid and optionvalue = 7)

如果這是一個獨家匹配,建議如下,“當選項值只匹配兩個不同的條件匹配第二個表”時,你可能還有第三個存在條件。 性能方面,這可能會開始瓦解。

AND NOT EXISTS (SELECT 1 FROM table2 WHERE table1.id=table2.masterid AND optionvalue  NOT IN (2,7)

編輯:關於相關子查詢的注釋, 其中一個更快:相關子查詢或連接?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM