2013-03-01 38 views
1

我有一個數據庫結構。問題在於表格非常複雜(typo3)。如果在其他列中有多於1個值,請選擇1行多個時間

我將簡化這個:

|  ID |CAT | 
|==========|=====| 
|1   |44,15| 
|2   |16 | 
|3   |29,30| 

我想有作爲的結果是1排爲每個類別(CAT),它的意思是

1 44 
1 15 
2 16 
3 29 
3 30 

我試圖用簡單的選擇但它當然不起作用。

我還試圖用左與桌類加入使用CATEGORY.id IN (TABLE1.cat)

+0

[你有什麼嘗試?](http://www.whathaveyoutried.com/)請參閱[問問建議](http://stackoverflow.com/questions/ask-advice)。 – 2013-03-01 16:40:37

+0

真正的sql很長,但我試圖用最簡單的方法來做。 – 2013-03-01 16:50:14

回答

0

如果你只有在貓兩個值:

select id, left(cat, locate(',', cat) - 1) 
from t 
where cat like '%,%' 
union all 
select id, substr(cat, locate(',', cat) + 1, length(cat)) 
from t 
where cat like '%,%' 
union all 
select id, cat 
from t 
where cat not like '%,%' 

如果你有一個類別列表,那麼你可以做到以下幾點:

select t.id, c.cat 
from t join 
    categories c 
    on concat(',', c.cat, ',') like concat('%,', t.cat, ',%') 
相關問題