2015-11-25 164 views
0

這裏是我的數據結構:MySQL查詢CONCAT工作不正常

table: items 
id name   category1 category2 category3 
-------------------------------------------------- 
1 apple  1   57   NULL 
2 banana  1   41   55 
3 orange  1   53   NULL 
4 strawberry 1   NULL  NULL 

所需的輸出:

id name   categories 
-------------------------------------------------- 
1 apple  1,57 
2 banana  1,41,55 
3 orange  1,53 
4 strawberry 1 

,這裏是我的查詢:

SELECT items.*, CONCAT(category, ",", category2, ",", category3) AS categories FROM toom_items 

東西不工作,我很得到這個:

id name   categories 
-------------------------------------------------- 
1 apple  NULL 
2 banana  NULL 
3 orange  NULL 
4 strawberry NULL 

任何想法有什麼問題嗎?

+1

我建議你使用'concat_ws()',因爲你只需要像'concat_ws(「,」,category,category2,category3)''一樣編寫分隔符''。 – vincent

+0

幫助..謝謝! – Fuxi

回答

0

我認爲你是從第一類失蹤「1」:更新這樣的查詢:

SELECT items.*, CONCAT(category1, ",", category2, ",", category3) AS categories FROM toom_items 

OR請使用串連這樣的:

CONCAT_WS(',', category1, category2, category3); 
0

我已經發現了兩個錯誤的東西在你的問題。

首先,您的查詢:

SELECT items.*, CONCAT(category, ",", category2, ",", category3) AS categories FROM toom_items 

你應該是指表items因爲在給定的例子,你沒有toom_items表。

其次,給出您的查詢,您得到的結果與您的查詢不符。既然你的領域選擇items.*那麼就應該是這樣的:

| id | name  | category1 | category2 | category3 | categories | 
+------+------------+-----------+-----------+-----------+------------+ 
| 1 | apple  |   1 |  57 |  NULL | NULL  | 
| 2 | banana  |   1 |  41 |  55 | NULL  | 
| 3 | orange  |   1 |  53 |  NULL | NULL  | 
| 4 | strawberry |   1 |  NULL |  NULL | NULL  | 

要回答這個問題,我想你的結構和正確的查詢應該是:

SELECT id, name, CONCAT_WS(',', category1, category2, category3) as 'categories' FROM items; 

其結果將是:

+------+------------+------------+ 
| id | name  | categories | 
+------+------------+------------+ 
| 1 | apple  | 1,57  | 
| 2 | banana  | 1,41,55 | 
| 3 | orange  | 1,53  | 
| 4 | strawberry | 1   | 
+------+------------+------------+ 

參考截圖:

CONCAT_WS Query