Fetching only rows that match all entries in a joined table (SQL)

前端 未结 2 1516
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-15 06:09

I have the following five tables:

  • ISP
  • Product
  • Connection
  • AddOn
  • AddOn/Product (pivot table for many-to-many relationship).
相关标签:
2条回答
  • 2021-01-15 06:52

    You could add to the WHERE clause:

    AND NOT EXISTS (SELECT NULL FROM addon a2
                    WHERE  a2.addon_id IN (1,14,237)
                    AND NOT EXISTS
                    ( SELECT NULL
                      FROM   product_addon pa2
                      WHERE  pa2.addon_id = a2.addon_id
                      AND    pa2.product_id = p.product_id
                    )
                   )
    

    Or equivalently:

    AND NOT EXISTS (SELECT NULL FROM addon a2
                    LEFT JOIN product_addon pa2
                      ON pa2.addon_id = a2.addon_id
                     AND pa2.product_id = p.product_id
                    WHERE a2.addon_id IN (1,14,237)
                    AND   pa2.product_id IS NULL
                    )
                   )
    
    0 讨论(0)
  • 2021-01-15 06:53
    GROUP BY set-of-column
    HAVING SUM(CASE WHEN ISNULL(pa.addon_id, 0) IN (1,14,237) THEN 1 ELSE 0 END) = 3
    
    0 讨论(0)
提交回复
热议问题