【问题标题】:Nesting subqueries with joins使用连接嵌套子查询
【发布时间】:2014-01-31 22:53:01
【问题描述】:

我正在尝试合并 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 

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

【问题讨论】:

    标签: mysql sql select join inner-join


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 2017-05-31
      • 2019-05-05
      • 2014-05-12
      相关资源
      最近更新 更多