在这种情况下,如何从多个 mysql 表中选择数据?
好吧,我有一个奇怪的场景,我无法更改数据库结构,因为我没有权限.对于这个问题,我有三个表
Ok I have a bit of a weird scenario, and I can't change the database structure, because I don't have the permission for that. For the problem, i have three tables
表 1-
id(int) | name(varchar) | link_id(int) | link_to(tinyint)
..............................................................
1 | value1 | 1 | 2
2 | value2 | 3 | 2
3 | value3 | 1 | 3
4 | value4 | 2 | 3
5 | value5 | 3 | 3
表 2-
id(int) | data(varchar)
............................
1 | some1
2 | some2
3 | some3
表 3-
id(int) | data(varchar)
............................
1 | another1
2 | another2
3 | another3
现在让我解释一下:在 table 1
中,link_id
是 table 2
或table 3
和 link_to
说明它是链接到表 2 还是表 3.
Now let me explain: in table 1
, link_id
is the id
field of either table 2
or table 3
, and link_to
states whether it is linked to table 2 or 3.
现在我需要从所有 3 个表中获取组合数据,以便针对 table 1
中的每个 name
字段,我得到 data
正确表中的字段,由该行中的 link_id 和 link_to 字段定义.
Now I need to fetch the combined data from all 3 tables such that, against each name
field in table 1
, I get the data
field from the correct table as defined by the link_id and link_to fields in that row.
是否有任何 mysql 查询可以实现此目的?
Is there any mysql query for achieving this?
您可以尝试使用 UNION
You could try with a UNION
(
SELECT t1.id,t2.data
FROM table1 t1
INNER JOIN table2 t2 ON t1.link_id=t2.id AND t1.link_to=2
) UNION (
SELECT t1.id,t3.data
FROM table1 t1
INNER JOIN table3 t3 ON t1.link_id=t3.id AND t1.link_to=3
)