2013-08-23 39 views
0

简单的问题一个SELECT:CONCAT组中的另一SELECT

有2个表:

  1. 流派[名称,songID]

  2. 宋[ID,标题,用户ID,状态]

    SELECT id,name,title,userID,status FROM songs INNER JOIN genre ON song.id = genre.songID ORDER BY id ASC;

什么是查询从

+----+-------------+----------------------+--------+--------+ 
| id | genre.name | song.title   | userID | status | 
+----+-------------+----------------------+--------+--------+ 
| 1 | tech  | Feel it all   |  1 |  1 | 
| 2 | tech  | Tester    |  1 |  1 | 
| 3 | music  | Sejujurnya   |  1 |  1 | 
| 4 | music  | Not Done    |  1 |  1 | 
| 5 | life  | Cinta    |  1 |  1 | 
| 6 | life  | Feel it all   |  1 |  1 | 
| 7 | life  | Not Done    |  1 |  1 | 
| 8 | truth  | Tester    |  1 |  1 | 
| 9 | tree  | Tester    |  1 |  1 | 
| 10 | climb  | Tester    |  1 |  1 | 
+----+-------------+----------------------+--------+--------+ 

+----+-------------+---------------------------------+--------+--------+ 
| id | genre.name | song.title      | userID | status | 
+----+-------------+---------------------------------+--------+--------+ 
| 1 | tech  | Feel it all,Tester    |  1 |  1 | 
| 2 | music  | Sejujurnya, Not Done   |  1 |  1 | 
| 3 | life  | Cinta, Feel it all, Note Done |  1 |  1 | 
| 4 | truth  | Tester       |  1 |  1 | 
| 5 | tree  | Tester       |  1 |  1 | 
| 6 | climb  | Tester       |  1 |  1 | 
+----+-------------+---------------------------------+--------+--------+ 

感谢

+0

可能的重复http://stackoverflow.com/questions/4650744/mysql-multiple-row-to-single-row –

+0

我想我看到一个模式,来自同一流派的标题是内爆的,但然后'暗夜'和'布卡'有什么关系?他们甚至不在原来的桌子上。 –

+1

查看MySQL中的[GROUP_CONCAT-function](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat)。 @Declan_K:你的链接是针对SQL服务器的,稍有不同。 –

回答

1

得到的结果使用GROUP_CONCAT与GROUP BY

SELECT 
    id, 
    genre.name, 
    GROUP_CONCAT(title) as title, 
    userID, 
    status 
FROM 
    songs 
INNER JOIN 
    genre 
ON 
    song.id=genre.songID 
GROUP BY 
    genre.name 
ORDER BY 
    id ASC 
+0

了不起的工作朋友。真棒。 – AFwcxx

+0

@AFwcxx这里返回的'id'字段在这里没有任何意义,因为它只涉及其中一首歌曲,您可以将concat更改为'GROUP_CONCAT(CONCAT(id,“ - ”,title))作为标题, '这样你仍然可以得到带有标题的歌曲的ID,并将它们分割成你的代码,即'explode(“ - ”,$ title);' –

0
SELECT 
    `Songs`.`id`, 
    `Genre`.`Name`, 
    GROUP_CONCAT(`Songs`.`Title`) as Title, 
    `Songs`.`userID`, 
    `Songs`.`status` 
FROM 
    `Genre`, 
    `Songs` 
WHERE 
    `Genre`.`SongID` = `Songs`.`id` 
GROUP BY 
    `Genre`.`Name`