concat在另一个SELECT中组合一个SELECT

时间:2013-08-23 17:30:04

标签: php mysql sql

简单问题:

有2个表:

  1. 流派[name,songID]

  2. 歌曲[id,title,userID,status]

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

  3. 获取结果的查询是什么
    +----+-------------+----------------------+--------+--------+
    | 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 |
    +----+-------------+---------------------------------+--------+--------+
    

    由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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`