Inner Join Many to Many Tables with Filter In MySQL

后端 未结 3 2035
迷失自我
迷失自我 2021-01-17 08:58

table structure ....Here is only 3 tables.. (bought ,customer,product). ..

bought table structure : fields (id,product_id,customer_id), 
customer table struc         


        
3条回答
  •  醉酒成梦
    2021-01-17 09:47

    I want to get customers who bought product 'a' but did not buy products 'b'

    Try this:

    SELECT * 
    FROM Customers c
    INNER JOIN
    (
         SELECT * 
         FROM bought 
         WHERE product_id = id of 'a'
    ) ba ON c.CustomerId = ba.CustomerId
    LEFT JOIN
    (
         SELECT * 
         FROM bought 
         WHERE product_id = id of 'b'
    ) bb ON c.CustomerId = bb.CustomerId
    WHERE bb.CustomerId IS NULL;
    

提交回复
热议问题