我有一个名为table_name(table_a)的列的表。这是我数据库中另一个表的名称。 e.g。
table_a
=========
id table_name group_id
------------------------------
1 table_b 1
2 table_b 1
3 table_c 1
4 table_d 2
table_b
=========
id val table_a_id
-------------------------
1 val1 1
2 val2 2
3 val3 10
table_c
=========
id val table_a_id
-------------------------
1 val4 3
table_d
=========
id val table_a_id
-------------------------
1 val5 4
2 val6 5
我想编写单个查询,该查询将根据group_id为table_a中的每一行返回val
。例如,如果我使用group_id = 1
,我将从单个查询返回val1, val2, val4
。返回的值不必是逗号分隔的ilist,它可以是列或任何东西,重要的是我可以在单个查询中执行它
答案 0 :(得分:3)
SELECT val FROM table_a
INNER JOIN
SELECT * FROM (
SELECT 'tabel_b' as table_name, id, val, table_a_id FROM table_b
UNION
SELECT 'tabel_c' as table_name, id, val, table_a_id FROM table_c
UNION
SELECT 'tabel_d' as table_name, id, val, table_a_id FROM table_d
) u_tables ON (u_tables.table_a_id = table_a.id
/* This part is optional, because the u_tables.table_a_id already links
to a unique key in table_a and thus the link to table_name is not needed
AND table_a.table_name = u_tables.table_name)
if I've missed something in your idea/design you can use it if you want*/
)
WHERE table_a.id = 1
它不会赢得任何速度或优雅设计的价格,但只要桌子尺寸足够小就应该有效。
如果您确实不需要链接到u_tables.table_name
,则可以通过多种方式加快查询速度。