MySQL,通过表2中的引用获取描述表1中一个产品的所有行

时间:2016-02-26 19:08:46

标签: mysql

我需要找到所有属性&产品的图像。 每个产品都在表1中的type列中标记。 这些属性也在表1中定义,每个属性都在一个单独的行上。

这是表结构的简化版本:

Table 1:
id | type     | value   | url
1  | product  | T-shirt |    
2  | image    |         | http://www......
........
15 | size     | XXL     | 
........
18 | color    | blue    |

Table 2:
id | ref_id | link_id   
1  | 1      | 1
2  | 1      | 2
3  | 1      | 15
4  | 1      | 18

产品及其属性之间的关系在表2中定义:
- ref_id与表1中的ID匹配我们想要的产品 - link_id持有一个id(来自表1),该ID是产品本身或产品的属性

因此,在此示例中,表1中的id 1在表2中有4个出现(ref_id = 1):产品行和3个属性行(imagesize & color) 它们由表2中的link_id列引用。

如果可能的话,我想在1个查询中解决这个问题,但我仍然坚持如何解决'反向引用'。 一旦我在表1中找到了产品的ID,我就可以得到表2中的link_id,但是如何再次使用它们(在同一个查询中)才能获得表1中的行。

在1个查询中是否完全可以,或者我应该为此使用2个单独的查询?

更新:
这是我走了多远:

SELECT      t1.id, t1.type, t1.value, t1.url,  
            t2.link_id
FROM        table_1 t1
LEFT JOIN   table_2 t2
ON          t1.id = t2.ref_id
WHERE       t1.type = 'product' 

但在此之后,我不知道如何根据'反向引用来构建其余查询。

1 个答案:

答案 0 :(得分:0)

您可以再次加入table_1

SELECT      t1.id, t1.type, t1.value, t1.url,  
            t2.link_id, t1_attributes.type, t1_attributes.value
FROM        table_1 t1
LEFT JOIN   table_2 t2
ON          t1.id = t2.ref_id
LEFT JOIN   table_1 t1_attributes ON t2.link_id = t1_attributes.id
WHERE       t1.type = 'product' 

但是,这会为每个属性提供1行。如果您想为每种类型的属性添加字段,则必须为每个属性进行连接。

SELECT      t1.id, t1.type, t1.value, t1.url,  
            t2.link_id, t1_image.value, t1_size.value
FROM        table_1 t1
LEFT JOIN   table_2 t2 ON t1.id = t2.ref_id
LEFT JOIN   table_1 t1_image ON t2.link_id = t1_image.id
LEFT JOIN   table_1 t1_size ON t2.link_id = t1_size.id
WHERE       t1.type = 'product' AND t1_image.type = 'image' AND 
            t1_size.type = 'size'