2013-03-04 71 views
1

我有和this person一樣的確切問題,但是對於MySQL而不是SQL Server。可以用MySQL完成取消組合嗎? MySQL不幸的是沒有「Unpivot」功能。這裏是什麼,我需要一個例子:MySQL查詢取消組合數據

原始數據:

---------------------------------- 
owner id | name | occurances 
---------------------------------- 
1  | red  | 4 
1  | yellow | 2 
1  | green | 3 
---------------------------------- 

查詢輸出:

--------------- 
id | name 
--------------- 
1 | red 
1 | red 
1 | red 
1 | red 
1 | yellow 
1 | yellow 
1 | green 
1 | green 
1 | green 
--------------- 

回答

0

你需要一套這個數字。這裏有一種方法:

select id, name 
from t join 
     (select d1.d + 10 * d2.d + 100*d3.d as num 
     from (select 1 as d union all select 2 union all select 3 union all 
       select 4 union all select 5 union all select 6 
       select 7 union all select 8 unin all select 9 union all select 0 
      ) d1 cross join 
       (select 1 as d union all select 2 union all select 3 union all 
       select 4 union all select 5 union all select 6 
       select 7 union all select 8 unin all select 9 union all select 0 
      ) d2 cross join 
       (select 1 as d union all select 2 union all select 3 union all 
       select 4 union all select 5 union all select 6 
       select 7 union all select 8 unin all select 9 union all select 0 
      ) d3 
     ) n 
     where n.num between 1 and occurrences 

這適用於人數達到999

+0

這是MySQL的一個有效的解決方案,謝謝。 – Mike 2013-03-10 20:13:41