如何编写查询以通过逗号分隔成php中的单行来获取不同行的列值

时间:2017-02-15 08:56:34

标签: php mysql

执行此查询后:

`select A.idrequirement , A.title  , A.location , A.companyname,
 A.createdby, B.assignto from " . $_schema . ".requirement A, 
req_assignto_link B where A.createdby = '".$user."' and 
A.idrequirement=B.sourceid order by A.createdon`  ;

我有这样的事情:

由assignto创建的idrequirement title location companyname

25         Android   Banglore  Barclays     mangesh    ninad 
25         Android   Banglore  Barclays     mangesh    mangesh

但我想要这样的事情,

idrequirement |标题|位置|公司名称|由|创建assignto

25         | Android | Banglore  | Barclays  | mangesh   | ninad,mangesh

任何人都可以告诉你该怎么做?

2 个答案:

答案 0 :(得分:2)

我们可以将MySQL GROUP_CONCAT()用于此目的:

SELECT idrequirement,
       title,
       location,
       companyname,
       createdby,
       GROUP_CONCAT(assignto) AS assignto
FROM yourTable
GROUP BY idrequirement,
         title,
         location,
         companyname,
         createdby
对于查询中的每个组,

GROUP_CONCAT()将使用CSV格式汇总指定为输入的列的所有值。

答案 1 :(得分:0)

会是这样的

"select A.idrequirement , A.title , A.location , A.companyname, A.createdby,
GROUP_CONCAT(B.assignto) AS assignto 
FROM " . $_schema . ".requirement A, req_assignto_link B
WHERE A.createdby = '".$user."' and A.idrequirement=B.sourceid
GROUP BY A.idrequirement ";