Вопрос

У меня есть две таблицы в моей базе данных:

<Сильные> продукты

    .
  • id (int, первичный ключ)
  • имя (varchar)

    <Сильные> ПродуктыTags

      .
    • 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 бессмыслен, потому что никакие строки не будут возвращены.

Это было полезно?

Решение

This type of problem is known as relational division

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*/

Другие советы

you need to have a group by / count to ensure all are accounted for

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 

The MySQL WHERE fieldname IN (1,2,3) is essentially shorthand for WHERE fieldname = 1 OR fieldname = 2 OR fieldname = 3. So if you aren't getting the desired functionality with WHERE ... IN then try switching to ORs. If that still doesn't give you the results you want, then perhaps WHERE ... IN is not the function you need to use.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top