2016-11-27 65 views
0

您好我有与数据库表:产品,product_colors,颜色。SQL如何选择参数的父ID或ID(如果没有父)

产品有属性:ID,姓名,...

Product_colors有属性:ID,products_id,colors_id

颜色有属性:ID,colors_id ,名称

因此,产品有行中产品的颜色由products.id = product_colors.products_id 和未来连接加入跨product_colors.colors_id = colors.id

产品以colors_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 

红 - > flashred,橙色

绿色 - >猕猴桃,浅绿,深绿

我怎样才能得到它包含了所有家长的颜色(如parametr)所有的产品,如果参数的颜色是红色,浅绿 - >比选定的产品应该有颜色红色和绿色正好

所以我需要得到参数颜色的父(如果参数没有父我采取参数颜色),这种父母的颜色给这个数组一个选择产品的数组。 我想这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

+0

查看COALESCE()。 – Strawberry

+0

请分享预期结果。 –

+0

Kumar_Vikas是我添加了示例表,我想要参数颜色:1,5获取产品ID为1 – Petr

回答

0

该解决方案将涉及再重新加入到COLORS表格,以获得父级颜色数据。

如果您有其他加入这样的:

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

然后你就可以使用这个PARENT_COLOR表以显示或从该表中筛选结果。