MySQL select join where AND where

后端 未结 3 1127
忘了有多久
忘了有多久 2020-12-14 21:10

I have two tables in my database:

Products

  • id (int, primary key)
  • name (varchar)

ProductTags

3条回答
  •  隐瞒了意图╮
    2020-12-14 22:06

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

提交回复
热议问题