2011-04-01 71 views
1
I have a table: 
id name 
1 home 
2 menu 
3 contact 

second table: 
id name menu_id 
1 menu1 2 
2 menu2 2 
3 menu3 2 

and I need this output: 
1 home 
2 menu 
    1 menu1 2 
    2 menu2 2 
    3 menu3 2 
3 contact 

我試過這個聯盟但我失敗了。 有人知道在這裏使用什麼查詢? 謝謝!mysql難以查詢的聯盟

+0

你需要以嵌套的方式的菜單項?像嵌套的gridview或什麼的? – Remy 2011-04-01 11:24:57

回答

2
select t1.id, t2.id, t1.name, t2.name 
    from t1 
    left join t2 on t2.menu_id = t1.id 
order by t1.id, t2.id; 

好吧,如果你想有一個數據集就像你貼一個,這裏是查詢做到這一點:

select case 
     when t1Id < 0 then null 
     else t1Id 
     end as t1Id, nullif(t2Id, 0) as t2Id, t1Name, t2Name 
    from (
    select id as t1Id, 0 as t2Id, name as t1Name, null as t2Name 
     from t1 
     union 
    select -menu_id as t1Id, id as t2Id, null as t1Name, name as t2Name 
     from t2 
    ) allTables 
    order by abs(allTables.t1Id), abs(allTables.t1Id) * 100 + allTables.t2Id; 
+0

感謝這與我所得到的一樣,但它需要是聯合查詢。這就是我的同事告訴我的,我不知道爲什麼 – Ruben 2011-04-01 11:21:16

+0

我編輯了這個查詢來顯示你想要的方式。我假設每個菜單選項的子菜單不超過100個。如果有:)則在'order by'子句中增加100 – 2011-04-01 11:43:53