它应该是如此简单,但也许葡萄酒已经走到了我的脑海。
表A(需要部分的东西)
id | Name | part1 | part2 | part 3 | part 4 | etc
1 | This thing | 1 | 2 | 3 | 2 | etc
2 | another thing | 1 | 1 | 4 | 5 | etc
3 | even more | 11 | 2 | 2 | 2 | etc
表B(部分)
id | Description
1 | I am a part
2 | I am another Part
3 | Im a very imprtant part
A ;;我实际需要做的是通过“描述”
选择每个“东西”所需的所有“部分”所以我用英语而不是ID no
获得每一行即
id | Thing name | part 1 | part 2 | part 3 | part 4
1 | This Thing | name of part | name of part | name of part | name of part
就像我说的那样,完全记忆超载,我失去了生存的意志。任何帮助非常感谢收到。提前谢谢。
答案 0 :(得分:2)
它看起来像这样。我写了一个MySQL查询已经有一段时间了。我相信有人可以改进它。
SELECT
a.id,
a.name,
b1.description,
b2.description,
b3.description,
b4.description
FROM
table_a `a`
LEFT JOIN
table_b `b1`
ON a.part1 = b1.id
LEFT JOIN
table_b `b2`
ON a.part2 = b2.id
LEFT JOIN
table_b `b3`
ON a.part3 = b3.id
LEFT JOIN
table_b `b4`
ON a.part4 = b4.id
答案 1 :(得分:2)
您的数据模型从一开始就注定了复杂性。
select
*
from TableA A
left join TableB B1 on A.part1 = B1.id
left join TableB B2 on A.part2 = B1.id
left join TableB B3 on A.part3 = B1.id
left join TableB B4 on A.part4 = B1.id
这是未经测试的,但如果你" unpivot" TableA开辟了更多可能性。 的 e.g。强>
SELECT
A.id
, A.Name
, GROUP_CONCAT(B.Description ORDER BY A.rowno) as PartsList
FROM (
SELECT
A1.id
, A1.Name
, cj.rowno
, CASE
WHEN cj.rowno = 1 THEN part1
WHEN cj.rowno = 2 THEN part2
WHEN cj.rowno = 3 THEN part3
WHEN cj.rowno = 4 THEN part4
END AS LinkID
FROM TableA a1
CROSS JOIN ( 1 AS rowno
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
) cj
) A
LEFT JOIN TableB B ON A.LinkId = B.ID
GROUP BY
A.id
, A.Name
并且,如果TableA永久标准化,您将不需要这些复杂性。