这是我的表结构:
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
如何获得所需的结果?
答案 0 :(得分:0)
GROUP_CONCAT
或简单地CONCAT
:
SELECT order_id,CONCAT(username,' on ',created_at,' ',comments)
FROM order_comments
ORDER BY order_id;
另一种方法是CONCAT_WS
>与分隔符连接:
SELECT order_id,CONCAT_WS(' ',username,'on',created_at,comments)
FROM order_comments
ORDER BY order_id;
答案 1 :(得分:0)
尝试这个
select *
from (SELECT order_id, GROUP_CONCAT(
DISTINCT CONCAT(username,’ on ‘, created_at, ‘:’, comment order by id desc SEPARATOR '\n') as comments
FROM `order_comments`
group by order_id) comments