-- 示例代码:使用 GROUP_CONCAT 函数将多个行合并为一个字符串
-- 创建示例表
CREATE TABLE orders (
order_id INT,
product_name VARCHAR(100),
customer_id INT
);
-- 插入示例数据
INSERT INTO orders (order_id, product_name, customer_id) VALUES
(1, 'Product A', 101),
(2, 'Product B', 101),
(3, 'Product C', 102),
(4, 'Product D', 102),
(5, 'Product E', 103);
-- 使用 GROUP_CONCAT 将每个客户的订单合并为一个字符串
SELECT
customer_id,
GROUP_CONCAT(product_name SEPARATOR ', ') AS products
FROM
orders
GROUP BY
customer_id;
-- 解释:
-- 1. GROUP_CONCAT 函数用于将多行的值合并成一个字符串。
-- 2. SEPARATOR 参数指定合并时使用的分隔符,默认是逗号。
-- 3. 在这个例子中,我们将每个客户的订单产品名合并为一个字符串,并按客户 ID 分组。
上一篇:mysql 表增加字段
下一篇:mysql 建索引
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站