mysql结果格式转换成单行

时间:2016-02-10 05:36:42

标签: mysql

查询 -

select count(*) Jobs, partners.name Partner 
from jobs,customers, partners 
where customers.partner_id = partners.id 
and jobs.customer_id = customers.u_key 
and (jobs.status=100 or jobs.status=8) 
and jobs.created_at between '2016-02-08 00:00:00' and '2016-02-09 00:00:00'    
group by customers.partner_id; 

我的SQL查询结果就像

+------+----------+
| Jobs | Partner  |
+------+----------+
|    2 | Peter    |
|    2 | POLO     | 
|   24 | Pilot    |
+------+----------+

如何在mysql中格式化它以显示结果,如2 Peter,2 POLO,24 Pilot。可能吗?

2 个答案:

答案 0 :(得分:1)

是的,这是可能的。您需要做的就是使用concat函数组合两列。

以下是这样做的方法:

select concat(jobs,' ',partner);

答案 1 :(得分:1)

使用CONCATGROUP_CONCAT

<强>查询

SELECT GROUP_CONCAT(CONCAT(Jobs, ' ', Partner) separator ',') AS new_column
FROM my_table;

<强>结果

+-------------------------+
| new_column              |
+-------------------------+
| 2 Peter,2 POLO,24 Pilot |
+-------------------------+

SQL Fiddle Demo

Edit:

<强>查询

select  GROUP_CONCAT(CONCAT(t.Jobs, ' ', t.Partner) separator ',') as new_column from
(
    select count(*) Jobs, partners.name Partner 
    from jobs,customers, partners 
    where customers.partner_id = partners.id 
    and jobs.customer_id = customers.u_key 
    and (jobs.status=100 or jobs.status=8) 
    and jobs.created_at between '2016-02-08 00:00:00' and '2016-02-09 00:00:00'    
    group by customers.partner_id
)t;