使用连接嵌套子查询

时间:2014-01-13 08:55:03

标签: mysql sql select join inner-join

我正在尝试合并4个表,以获取服装项目的相应数据,在选择每个项目时都是这样的。

Array(
[0] => array ([item] => 1, [article] => 10, [layer1] => 6, [layer2] => 8, [layer3] => 9, [layer4] => 10), 
[1] => array ([item] => 2, [article] => 5, [layer1] => 3, [layer2] => 4, [layer3] => 5, [layer4] => 0/null),
[2] => array ([item] => 3, [article] => 7, [layer1] => 7, [layer2] => 0/null etc), 
[3] => array ([item] => 4, [article] => 1, [layer1] => 1, [layer2] => 2, [layer3] => 0/null etc))

我不确定如何嵌套和连接这些表来获取正确的数据,但是(不幸的是)所有4个表都需要存储各种排序和预览数据,最下面的表位于树下(article_layers,和图层)需要多行连接。骨架表如下所示。

items table
item_id   item_article   item_name
1          10             red dress
2          5              green polo
3          7              jeans
4          1              black leather jacket
5          10             black dress

articles table
article_id  article_name  
1            jacket
5            shirt
7            pants
10           dress

article_layers table
id    article_id    layer_id
1        1            1
2        1            2
3        5            3
4        5            4
5        5            5
6        7            7
7        10           6
8        10           8
9        10           9
10       10           10

layers table 
layer_id    layer_name    
1            jacket_right_sleeve
2            jacket_left_sleeve
3            shirt_right_sleeve
4            shirt_left_sleeve
5            shirt_torso
6            dress_torso
7            pants
8            dress_left_sleeve
9            dress_right_sleeve
10           dress_skirt

我试过

 SELECT items.*, articles.*, article_layers.*, layers.*, 
   (SELECT * FROM layers where article_layers.layer_id = layers.layer_id) as layer1,          
FROM items 
JOIN articles ON items.article_id = articles.article_id 
JOIN article_layers ON articles.article_id = article_layers.article_id 

和许多类似的查询,但我找不到神奇的公式来获取我需要的数据。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT *      
FROM items i 
INNER JOIN articles a ON i.article_id = a.article_id 
INNER JOIN article_layers al ON a.article_id = al.article_id
INNER JOIN layers l ON al.layer_id = l.layer_id