13

データベースに2つのテーブルがあります。

製品

  • id(int、主キー)
  • 名前(varchar)

ProductTags

  • product_id(int)
  • tag_id(int)

すべてのタグが付いている商品を選びたいのですが。私は試した:

SELECT
    *
FROM
    Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE
    ProductTags.tag_id IN (1, 2, 3)
GROUP BY
    Products.id

しかし、それは私にすべての与えられたタグを持っているのではなく、与えられたタグのどれかを持っている製品を与えます。WHERE tag_id = 1 AND tag_id = 2行が返されないため、書き込みは無意味です。

4

3 に答える 3

21

このタイプの問題は、関係除算として知られています

SELECT Products.* 
FROM Products
JOIN ProductTags ON Products.id = ProductTags.product_id
WHERE ProductTags.tag_id IN (1,2,3)
GROUP BY Products.id /*<--This is OK in MySQL other RDBMSs 
                          would want the whole SELECT list*/

HAVING COUNT(DISTINCT ProductTags.tag_id) = 3 /*Assuming that there is a unique
                                              constraint on product_id,tag_id you 
                                              don't need the DISTINCT*/
于 2011-02-16T14:35:08.153 に答える
0

MySQLWHERE fieldname IN (1,2,3)は本質的に。の省略形ですWHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3。したがって、で目的の機能が得られない場合は、 sWHERE ... INに切り替えてみてくださいOR。それでも希望する結果が得られない場合は、WHERE ... IN使用する必要のある関数ではない可能性があります。

于 2011-02-16T14:40:41.037 に答える
0

すべてが確実に考慮されるように、group by/countが必要です。

select Products.*
  from Products 
         join ( SELECT Product_ID
                  FROM ProductTags
                  where ProductTags.tag_id IN (1,2,3)
                  GROUP BY Products.id
                  having count( distinct tag_id ) = 3 ) PreQuery
        on ON Products.id = PreQuery.product_id 
于 2011-02-16T14:37:29.037 に答える