3

Products、Tags、products_tags (Products と Tags の間の多対多) の 3 つのテーブルがあります。私のスキーマでは、製品にはゼロから多数のタグを含めることができ、タグにはゼロから多数の製品を含めることができます。特定のタグが付いている商品と、特定のタグが付いていない商品を選択したいと考えています。

製品表:

idproducts / 名前

1 / サムスンギャラクシー

2 /サムスンノート1

3 /サムスンノート2

4 / iphone 4gs

タグ表:

idtags / 単語

1 / サムスン

2 / ギャラクシー

3 / 注1

4 / 注2

5 / アイフォン

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

Samsung Galaxy が必要で、「samsung」のようなタグを定義し、「note1」と「note2」を持たないように定義した場合。これに対するクエリは何でしょうか。

PSおそらく EXISTS または NOT EXISTS を使用する必要があると思いましたが、それらをどのように使用すればよいかわかりません。

前もって感謝します

4

2 に答える 2

1

samsung note 1およびを含む samsung というタグを持つすべての要素が結合によって選択されるため、クエリが機能していませんsamsung 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'

いくつかの重要なリソース:

于 2012-09-27T23:35:06.767 に答える
0

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 句を満たす行は not in one を満足できない可能性があるため、あなたの試みは機能しません。サムスンもモバイルもnote1でもnote2でもない

上記は、samsung または mobile を取得するために 1 つの結合を実行してから、tags テーブルに (別のエイリアスで) 再度結合して、note1 または note2 タグのないすべてのものを取得します。

于 2012-09-27T22:19:47.400 に答える