mysql - Rewriting a select query -
i have rather simple (i think) question @ hand. example tables , result need provided below (in reality tables containt more columns , data, jest left relevant). there query returns need. however, dont rather crude way in works (i dont subqueries in general). question is, how can rewrite query automatically react more columns appearing in table2 in future? right if "z" column added table2, need modify each query in code , add 1 more relevant subquery. want select read entire content of table2 , translate id numbers corresponding strings table1.
table1
----------------- id |x | ----------------- 567 |aaa | 345 |bbb | 341 |ccc | 827 |ddd | 632 |eee | 503 |fff | 945 |ggg | 234 |hhh | 764 |iii | 123 |jjj | -----------------
table2
------------------------- id |x |y | ------------------------- 1 |123 |341 | 2 |567 |632 | 3 |345 |945 | 4 |764 |503 | 5 |234 |827 | -------------------------
the result need
----------------- |b | ----------------- jjj |ccc | aaa |eee | bbb |ggg | iii |fff | hhh |ddd | -----------------
the query have
select (select `x` `table1` `table2`.`x` `table1`.`id` limit 1) a, (select `x` `table1` `table2`.`y` `table1`.`id` limit 1) b `table2` order `id` desc;
you might want restructure data model:
instead of:
------------------------- id |x |y | ------------------------- 1 |123 |341 | 2 |567 |632 | 3 |345 |945 | 4 |764 |503 | 5 |234 |827 | -------------------------
you have:
---------------------- col_id |col | ---------------------- 1 |x | 2 |y | ---------------------- --------------------------- id |col_id |col_val | --------------------------- 1 |1 |123 | 1 |2 |341 | 2 |1 |567 | 2 |2 |632 | etc ---------------------------
probably not worth hassle (you need pivot when you're accessing multiple columns @ time) allow query want across current , future columns.
Comments
Post a Comment