我在确定SQL查询时遇到问题...
我正在处理两个表。第一个是套件结构(K),其中给定的套件通常具有多个组件(例如,套件K1具有组件K1_A和K1_B,套件K2具有组件K2_A,K2_B,K2_C等)。 :
+-----+------+
| Kit | Comp |
+-----+------+
| K1 | K1_A |
| K1 | K1_B |
| K2 | K2_A |
| K2 | K2_B |
| K2 | K2_C |
| K3 | K4 |
| K4 | K4_A |
| … | … |
+-----+------+
(简化显示为 K ,实际表中还有许多其他列和套件/组件,但未排序)
注意:表已从原始表更新。为了澄清起见,这里要观察的一件事是套件通常是多层次的,例如K3(套件)包含组件K4(comp),而K4套件中又包含组件K4_A等。
第二个表具有所有 item属性(I)(成本,现有库存等)作为两个套件和组件的行项目:>
+------+------------+------------+
| Item | Attr1 | Attr2 |
+------+------------+------------+
| K1 | (for K1) | (for K1) |
| K1_A | (for K1_A) | (for K1_A) |
| K1_B | (for K1_B) | (for K1_B) |
| K2 | (for K2) | (for K2) |
| K2_A | (for K2_A) | (for K2_A) |
| K2_B | (for K2_B) | (for K2_B) |
| K2_C | (for K2_C) | (for K2_C) |
| K3 | (for K3) | (for K3) |
| K4 | (for K4) | (for K4) |
| K4_A | (for K4_A) | (for K4_A) |
| … | … | … |
+------+------------+------------+
( I 同样以简化形式显示,以便于参考)
我试图加入表格,以便输出套件结构,其中显示了与套件的组件相关的属性,即以下所需结果:
+-----+------+------+------------+------------+
| Kit | Comp | Item | Attr1 | Attr2 |
+-----+------+------+------------+------------+
| K1 | K1_A | K1_A | (for K1_A) | (for K1_A) |
| K1 | K1_B | K1_B | (for K1_B) | (for K1_B) |
| K2 | K2_A | K2_A | (for K2_A) | (for K2_A) |
| K2 | K2_B | K2_B | (for K2_B) | (for K2_B) |
| K2 | K2_C | K2_C | (for K2_C) | (for K2_C) |
| K3 | K4 | K4 | (for K4) | (for K4) |
| K4 | K4_A | K4_A | (for K4_A) | (for K4_A) |
| … | … | … | … | … |
+-----+------+------+------------+------------+
(注意:我只是在寻找相对于套件低一个级别(即套件Lvl0至Comp Lvl1),而不是完整的递归BOM深度)
我尝试的SQL查询如下:
SELECT K.Kit, K.Comp, I.Item, I.Atrr1, I.Attr2
FROM K
JOIN I
ON K.Kit = I.Item
这是行不通的,因为它连接到 kits 的(重复)属性,而不是 components ,即以下错误的输出:
+-----+------+------+----------+----------+
| Kit | Comp | Item | Attr1 | Attr2 |
+-----+------+------+----------+----------+
| K1 | K1_A | K1 | (for K1) | (for K1) |
| K1 | K1_B | K1 | (for K1) | (for K1) |
| K2 | K2_A | K2 | (for K2) | (for K2) |
| K2 | K2_B | K2 | (for K2) | (for K2) |
| K2 | K2_C | K2 | (for K2) | (for K2) |
| K3 | K4 | K3 | (for K3) | (for K3) |
| K4 | K4_A | K4 | (for K4) | (for K4) |
| … | … | … | … | … |
+-----+------+------+----------+----------+
任何建议都值得赞赏。谢谢您的时间!
更新:添加了格式化表格和MySQL标记
答案 0 :(得分:3)
看起来您只是想加入comp?
SELECT K.Kit, K.Comp, I.Item, I.Atrr1, I.Attr2
FROM K
JOIN I
ON K.comp = I.Item