开发者

SQL Query to fetch all product categories and whether the product is in it

开发者 https://www.devze.com 2023-01-05 13:50 出处:网络
I have three tables. Product, product categories and product category links. The links table is there as a product can be in more than one category.

I have three tables. Product, product categories and product category links. The links table is there as a product can be in more than one category.

What I am trying to achieve is a list of ALL the categories with an additional field which states whether for that specific product id, if the product is in that category.

SELECT *, l.product_id as checked FROM `ProductCategories` LEFT JOIN ProductCategoriesLink l ON l.category_id开发者_运维百科 = ProductCategories.id WHERE ( l.product_id = 1 ) AND ( ProductCategories.id > 0 ) GROUP BY ProductCategories.id ;

However at the moment, this only retrieves the categories which the product is in.

Any advice appreciated.


SELECT
    ProductCategories.*,
    l.product_id IS NOT NULL AS ProductInCategory
FROM
    ProductCategories
    LEFT JOIN ProductCategoriesLink AS l ON
        ProductCategories.id = l.category_id AND
        l.product_id = 1

This makes use of the fact that when a LEFT JOIN is performed, at least one row is returned for every row on the left-hand table. If there weren't matching rows on the right-hand table, the columns from that table are all NULL.

0

精彩评论

暂无评论...
验证码 换一张
取 消