首先我要说的是,这是一种可怕的存储数据的方式,其次,这不是我的错:)我正在尝试与第 3 方数据库集成以提取存储在 3 个表中的信息,它实际上应该存储在两个 AND 中,其中表 2 具有多对一关系。由于情况并非如此,我有一个难题要分享。
表一包含可以存储多个值的行。每行都有 codeid1
-codeid20
。这些列可能包含一个值或 0(它们绝不是 null
)。它们还有一个相应的 codetype1
-codetype20
,可以是 0 或 1。
如果codetype1
等于0,我们将转到表2并从匹配的table1.codeid1=table2.id
中选择description
。如果 codetype1
等于 1,我们现在必须查看 table3 并找到 table1.codeid1=table3.id
的位置,然后匹配 table3.table2id=table2.id
并返回描述。
数据结构如下:
table1
codeid1,codeid2,codeid3,...codeid20 ... codetype1,codetype2,codetype3,.....codetype20
18 13 1 33 0 0 1 1
13 21 45 0 0 1 0 0
table2
id, description
13 Item 13 Description
15 Item 15 Description
17 Item 17 Description
18 Item 18 Description
21 Item 21 Description
28 Item 28 Description
45 Item 45 Description
table3
id, table2id
1 15
33 17
21 28
我想要的结果如下所示:
rowid, description
1 Item 18 Description
1 Item 13 Description
1 Item 15 Description
1 Item 17 Description
2 Item 13 Description
2 Item 28 Description
2 Item 45 Description
昨晚我开始与某人合作,但由于不集成 table3,我错过了部分复杂的情况。就像我说的,有趣的谜题...这给了我前两个表之间的关系,但我不确定如何在第三个表中工作。
SELECT table1.rowid, table2.description
FROM table2
INNER JOIN table1
ON table2.id=table1.codeie1
OR table2.id=table1.codeie2
...
数据库是通过ODBC连接的Faircom C-Tree DB,一般兼容Mysql语句,包括UNION、WITH、INTERSECT、EXISTS、JOIN...没有PIVOT功能。
最佳答案
也许它可以与 or
一起使用,而不是与 in
一起使用:
where exists (select 1
from table1 as t1
where t2.id = t1.codeid1 or
t2.id = t2.codeid2 or
. . .
);
关于mysql - 根据表 1 结果的条件,从连接 2 个或 3 个表的单行创建多个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48464936/