views:

18

answers:

1

Let's assume i have three table - list,a and b

table list
|a_id|--|b_id|--'name'
|4   |--|3   |--|foo|
|1   |--|2   |--|foo|

table a
|id|--|name|--|order|
|1 |--|a_1 |--|1    |
|2 |--|a_2 |--|2    |
.....................
|n |--|a_n |--|n    |

table b
|id|--|name|--|order|
|1 |--|b_1 |--|1    |
|2 |--|b_2 |--|2    |
.....................
|n |--|b_n |--|n    |

a_id in table list is id from a table, and

b_id in table list is id from b table

I need to get the name list from a and b tables ordered by their order, where name = 'foo' in list table.

ie. i need to get a_1,a_4 from table a, and b_2,b_3 from b.

I wrote a query like

SELECT
                    `a_1_table`.`name` a_1_name,
                    `b_1_table`.`name` b_1_name
                FROM
                    `list`
                LEFT JOIN 
                    `a_1` AS a_1_table ON ( `a_1_table`.`id` = `list`.`a_id` )
                LEFT JOIN 
                    `b_1` AS b_1_table ON ( `b_1_table`.`id` = `list`.`b_id` )
                WHERE 
                    `list`.`name` = 'foo'

but as i see, in such structure, i can't write order by .... ie. i can' but i will not get what i want.

What can i do?

Thanks much

+2  A: 

Use:

SELECT x.name
    FROM (SELECT a.name, a.order, 1 AS sort
            FROM LIST l
            JOIN a ON a.id = list.a_id
          WHERE l.name = 'foo'
          UNION ALL
          SELECT b.name, b.order, 2 AS sort
            FROM LIST l
            JOIN b ON b.id = list.b_id
           WHERE l.name = 'foo') x
ORDER BY x.sort, x.order

UNION ALL is faster than UNION, because it doesn't remove duplicates (which UNION does).

OMG Ponies