SQL如何选择parent ID或ID(如果没有父级)的参数



嗨,我有具有表格的数据库:产品,product_colors,颜色。

产品具有属性: id,名称,...

product_colors 具有属性: id,products_id,colors_id

颜色具有属性: id,color_id,name

使产品在产品颜色中的行加入产品。ID= product_colors.products_id以及product_colors.colors_id = colors.id

的下一个连接到color_id

产品:

id     name
-------------------
1      produkt1
2      produkt2
3      produkt3

product_colors:

id     products_id      colors_id
1      1                1 
2      1                5
3      2                1 
4      2                3
5      3                6

颜色可以在colors_id上具有父级:

id     colors_id      name
__________________________________
1      null           red
2      null           green
3      1              flashred
4      2              kiwi 
5      2              lightgreen
6      null           black

红色 ->闪光,橙色

绿色 ->猕猴桃,灯绿色,darkgreen

我如何获得包含所有父颜色的所有产品(作为参数),如果参数颜色是红色和浅色 ->比选定的产品应该具有红色和绿色的

因此,我需要获得参数颜色的父母(如果参数没有父母,我会采用参数颜色),则此父颜色在SELECT产品中由此数组usin adive Array a给出。我想在mysql

中做到这一点
SELECT products.id AS id
        FROM products
        LEFT JOIN product_colors
            ON products.id = product_colors.products_id
        LEFT JOIN colors
            ON product_colors.colors_id = colors.id
        WHERE colors.id IN (1,5)

1,5是参数

对于参数[1,5]我想获得ID 1

的结果产品

该解决方案将涉及再次加入颜色表,以获取父颜色数据。

如果您有这样的加入:

LEFT JOIN colors PARENT_COLOR ON colors.colors_id = PARENT_COLOR.id

然后,您可以使用此parent_color表显示或过滤此表中的结果。

相关内容

最新更新