mysql - 使用连接嵌套子查询

标签 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 

和许多类似的查询,但我找不到神奇的公式来获取我需要的数据。感谢您的帮助。

最佳答案

试试这个:

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

关于mysql - 使用连接嵌套子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087132/

相关文章:

mysql - XML 数据插入 MySql DB

php - 奇怪的加入php

sql - 如何从 JSONB 列中提取数据

php - 通过内爆数组运行 Where IN,但输出是一个字符串,并没有按预期在 MySQL 中运行

php - 如果值为 null 则跳过插入查询 Mysql

c# - 如何在 C# 的 TreeView 中显示选定节点的显示值?

mysql - 如何将 UPDATE WHERE IF @@ROWCOUNT == 0 查询从 MS SQL 转换为 MySQL?

php - 说服 IT 经理允许使用 SQL Server 而不是 Access

javascript - jQuery:绑定(bind) "CTRL+A"仅选择特定区域

SQL SELECT 列字母前缀