2012-02-08 62 views
0

I(至少對我)有一個相當複雜的問題MySQL數據庫多號顯示爲行

我有以下表結構

| id | roomtype | roomno | feature 
| 1 | STDK | 11 | BT 
| 2 | STDK | 11 | AE 
| 3 | STDK | 22 | SMK 
| 4 | STDK | 22 | BT 
| 5 | STDT | 33 | NONSMK 

,我想有這樣

輸出
Type: STDK - RoomNo: 11 - Features: BT, AE 
Type: STDK - RoomNo: 22 - Features: SMK, BT 
Type: STDT - RoomNo: 33 - Features: NONSMK 

它可能不是那麼複雜,但我不能得到它...

回答

5

這顯示了您正在查找的結果...但我不喜歡在查詢中格式化結果的想法!

select 
    concat("Type: ", roomtype, 
    " - RoomNo: ", roomno, 
    " - Features: ", group_concat(feature order by feature separator ', ')) 
    as result 
from t1 
group by roomtype, roomno 

這裏是一個工作example

+2

+1不喜歡在SQL所有格式的想法,並教我關於sqlize.com – 2012-02-08 06:25:34

+0

謝謝^。^還有一些其他有用的鏈接在我的個人資料中(我很懶,我甚至沒有把它們加上書籤):P – 2012-02-08 06:27:28

+1

我在我的一對夫婦jsfiddle.net鍋爐板設置。 – 2012-02-08 09:04:34

3

你可以使用MySQL的group_concat

select roomtype, roomno, group_concat(feature order by feature separator ', ') 
from your_table 
group by roomtype, roomno 
order by roomno 

生產從您完全格式化輸出留作練習。

0
SELECT 
    roomtype AS Type, 
    roomno AS RoomNo, 
    GROUP_CONCAT(feature ORDER BY feature SEPARATOR ', ') AS Features 
FROM 
    tableName 
GROUP BY roomtype, roomno 
ORDER BY roomno