簡體   English   中英

MySQL選擇連接多個表加上IN和NOT IN

[英]MySQL select join many to many tables plus IN and NOT IN

我有3個表:產品,標簽和products_tags(產品和標簽之間的多對多)。 在我的架構中,產品可以包含零到多個標簽,標簽可以包含零到多個產品。 現在我想選擇具有特定標簽且沒有特定標簽的產品。

產品表:

idproducts / name

1 /三星銀河

2 /三星note1

3 /三星note2

4 / iphone 4gs

標簽表:

idtags / word

1 /三星

2 / galaxy

3 / note1

4 / note2

5 / iphone

6 / 4gs

7 /蘋果

Products_Tags表:

產品/標簽

1/1

1/2

2/1

2/3

3/1

3/4

4/5

4/6

我有下面的查詢,但它給了我帶有我想要的標簽的產品,因為他們有一些其他的標簽,並且由於連接它們出現在結果集中。

SELECT * FR0M產品AS p

 JOIN products_tags AS pt ON pt.product = p.idproducts JOIN tags AS t ON t.idtags = pt.tag WHERE t.word IN ('samsung', 'mobile') AND t.word NOT IN ('note1', 'note2') 

如果我想要三星Galaxy和我定義的標簽像'samsung'而沒有'note1'和'note2'。 對此有什么疑問?

PS我想也許應該使用EXISTS或NOT EXISTS,但我只是無法弄清楚我應該如何使用它們。

提前致謝

您的查詢無法正常工作,因為聯接會選擇帶有標簽三星的所有元素,包括samsung note 1samsung note 2 您可以使用group_concat對所有標記名稱進行分組,然后使用likeRegexp對其進行過濾,如下所示:

select *, GROUP_CONCAT(t.word) tagname from products as p
  inner JOIN products_tags AS pt ON pt.products = p.productid
  inner Join tags t on t.idtags = pt.tags 
group by p.productid
having tagname not REGEXP 'note1|note2' 
   and tagname REGEXP 'samsung|mobile'

一些重要資源:

您想要所有帶有三星或手機標簽但沒有note 1或note2標簽的產品?

SELECT * FR0M products AS p

JOIN products_tags AS pt ON pt.product = p.idproducts

JOIN tags AS tp ON tp.idtags = pt.tag and (tp.word = 'samsung' or tp.word = 'mobile')

JOIN tags AS tn ON tn.idtags = pt.tag and tn.word <> 'note1' and tn.word <> 'note2'

將是一種方式。

你的嘗試不起作用,因為任何滿足in子句的行都不可能滿足於一個。 三星和手機都不是note1或note2

上面做了一個連接來獲取三星或移動,然后再次連接到標簽表(使用不同的別名)以獲得沒有note1或note2標簽的所有那些。

暫無
暫無

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

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