2017-10-04 43 views
1

我試圖避免傳遞兩個單獨的MySQL(版本5.6.37)查詢,並使用事務。我認爲這可以在單個查詢中完成,但是我需要知道我要出錯的地方。MySQL列扁平化爲字符串

如果我使用此查詢:

SELECT titles.t_id,title,cover,pageData.pageNum 
FROM titles 
    JOIN biblio  ON titles.t_id = biblio 
    JOIN pageData ON biblio.t_id = pageData.t_id 
WHERE titles.t_id = '1'; 

它成功地返回與冗餘數據的三列,只有一個新的數據列(P_ID)結果:

t_id | title    | cover | pageNum 
1 | The Art of the Deal | 32.jpg | 1 
1 | The Art of the Deal | 32.jpg | 2 
1 | The Art of the Deal | 32.jpg | 3 
1 | The Art of the Deal | 32.jpg | 4 
1 | The Art of the Deal | 32.jpg | 5 

我想有一種方法可以修改查詢,以便將pageNum列中的新數據展平爲單個結果(即從整數值轉換爲分隔字符串),如下所示:

t_id | title    | cover | p_id 
1 | The Art of the Deal | 32.jpg | 1,2,3,4,5 

我一直在SELECT中試驗一個子SELECT,但是我有一致的語法錯誤。 有沒有辦法將以下兩個查詢結合起來得到上述結果?

SELECT titles.t_id,title,cover 
FROM titles 
    JOIN biblio  ON titles.t_id = biblio 
WHERE titles.t_id = '1'; 

SELECT pageData.pageNum FROM pageData WHERE pageData.t_id = '1' 

回答

1

你需要可以使用MySQL功能GROUP_CONCAT()很容易完成的結果。
爲了產生一個有效的SQL查詢,並得到你所期望的結果,你還需要添加一個GROUP BY clause到查詢,並把它顯示的所有SELECT子句中的其他列:

SELECT titles.t_id, title, cover, GROUP_CONCAT(pageData.pageNum) AS p_id 
FROM titles 
    JOIN biblio  ON titles.t_id = biblio 
    JOIN pageData ON biblio.t_id = pageData.t_id 
WHERE titles.t_id = '1' 
GROUP BY titles.t_id, title, cover 
+0

所有偉大答案。這一個解釋它是最好的。非常感謝,每個人。 – Parapluie

3

您可以結合使用GROUP_CONCAT與GROUP BY了點。

SELECT 
    titles.t_id 
    , title,cover 
    , GROUP_CONCAT(pageData.pageNum) AS p_id 
FROM titles 
    JOIN biblio  ON titles.t_id = biblio 
    JOIN pageData ON biblio.t_id = pageData.t_id 
WHERE titles.t_id = '1' 
GROUP BY 
    t_id 
, title 
, cover 
2

使用GROUP_CONCAT函數。同時假設你的意思是JOIN biblio ON titles.t_id = biblio.t_id

SELECT t.t_id, title, cover, GROUP_CONCAT(pageData.pageNum) AS pageNum 
FROM titles t 
JOIN biblio b ON t.t_id = b.t_id 
JOIN pageData p ON b.t_id = p.t_id 
WHERE t.t_id = '1' 
GROUP BY t.t_id, title, cover