这是我的表结构:
orders
--------------------------
id | customer_name
--------------------------
23 | John Doe
24 | Jane Doe
order_comments
--------------------------------------------------------------------
id | order_id | username | created_at | comment
--------------------------------------------------------------------
1 | 23 | Bob | 2019-04-01 | my first comment
2 | 23 | Jim | 2019-04-03 | another comment
3 | 24 | Jim | 2019-04-05 | testing
4 | 24 | Jim | 2019-04-06 | testing again
我想选择换行连接的注释,但也包括用户名和created_at。这是我到目前为止:
select *
from (SELECT order_id, GROUP_CONCAT(`comment` order by id desc SEPARATOR '\n') as comments
FROM `order_comments`
group by order_id) comments
结果:
order_id | comments
--------------------------------
23 | my first comment
| another comment
--------------------------------
24 | testing
| testing again
这是我想要的结果,包括用户名,并为每个评论concat创建:
order_id | comments
--------------------------------
23 | Bob on 2019-04-01:
| my first comment
|
| Jim on 2019-04-03:
| another comment
---------------------------------
24 | Jim on 2019-04-05:
| testing
|
| Jim on 2019-04-06:
| testing again
我怎样才能得到理想的结果?
GROUP_CONCAT
或只是CONCAT
:
SELECT order_id,CONCAT(username,' on ',created_at,' ',comments)
FROM order_comments
ORDER BY order_id;
另一种方式是qazxsw poi>与分隔符连接:
CONCAT_WS
试试这个吧
SELECT order_id,CONCAT_WS(' ',username,'on',created_at,comments)
FROM order_comments
ORDER BY order_id;