开发者

mysql join on table defined in another table

I have a table with a column called table_name (table_a). This is the name of another table in my database. 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    开发者_如何学Go val5    4
2     val6    5

i want to write a single query which will return val for each row in table_a based on group_id. e.g if i used group_id = 1 i would get val1, val2, val4 returned from a single query. the returned value does not have to be a comma seperated ilist, it could be columns or anything, the important thing is that I can do it in a single query


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

It's not going to win any prices for speed or elegant design but it should work as long as table sizes are small enough.

If you really don't need to link to u_tables.table_name you can speed this query up in a number of ways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜