2016-03-01 38 views
0

你能幫忙找到解決方案嗎?MySQL,將特定的行列合併到另一行

我有此查詢

SELECT P.id, P.url, PT.name, PT.lang 
FROM cms_pages P 
INNER JOIN cms_pages_translations PT 
    ON PT.page_id = P.id 
ORDER BY P.id DESC LIMIT 10; 

返回是這樣的:

ID |  URL  |  NAME  | LANGUAGE   
--------------------------------------------------- 
1 | 'hello-word' | 'Hello world' | 1 
--------------------------------------------------- 
1 | 'hello-word' | 'Hola mundo'  | 2 
--------------------------------------------------- 
1 | 'hello-word' | 'Olá mundo'  | 3 
--------------------------------------------------- 
2 | 'now-online' | 'We're online' | 1 
--------------------------------------------------- 
2 | 'now-online' | 'Estamos online' | 2 
--------------------------------------------------- 
2 | 'now-online' | 'Estamos online' | 3 

我如何能實現的東西看起來喜歡這樣的:

ID |  URL  |  NAME_1  |  NAME_2  | NAME_3 
----------------------------------------------------------------------------- 
1 | 'hello-word' | 'Hello world' | 'Hola mundo' | 'Olá mundo' 
----------------------------------------------------------------------------- 
2 | 'now-online' | 'We're online' | 'Estamos online' | 'Estamos online' 
----------------------------------------------------------------------------- 
+0

這被稱爲'pivoting'。如果您知道潛在列的最大數量,則可以使用「條件聚合」。如果不是,你將不得不使用'動態sql'。這兩個例子都有很多例子。 – sgeddes

+0

@sgeddes我已經搜索,它並沒有幫助我很多,你能推薦我一個關於這些概念的好文章嗎? –

+0

你知道最多的語言嗎?它不超過3種語言/列嗎? – sgeddes

回答

0

如果你知道潛在語言的數量 - 這會導致瞭解額外列的數量 - 您可以e conditional aggregation。下面是基於關閉您的樣本數據的例子:

select id, url, 
    max(case when language = 1 then name end) name_1, 
    max(case when language = 2 then name end) name_2, 
    max(case when language = 3 then name end) name_3 
from <yourquery> 
group by id, url 

如果你不知道語言的數量,你將不得不使用dynamic sql建在飛行中的欄。