2012-02-08 80 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