如何使用 MySQL 中的 GROUP_CONCAT() 拼接多行的?


首先,我們建立一個表格 -

mysql> create table DemoTable (CountryName varchar(100));
Query OK, 0 rows affected (1.01 sec)

使用 insert 命令,在表格中插入一些記錄 -

mysql> insert into DemoTable values('US');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('AUS');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('UK');
Query OK, 1 row affected (0.19 sec)

使用 select 語句,顯示來自表格中的所有記錄 -

mysql> select *from DemoTable;

會產生以下輸出 -

+-------------+
| CountryName |
+-------------+
| US          |
| AUS         |
| UK          |
+-------------+
3 rows in set (0.00 sec)

以下是拼接多行的查詢。我們建立一個過程 -

mysql> DELIMITER //
mysql> CREATE PROCEDURE searchDemo(in stringValue varchar(255), out output text)
   BEGIN
      select group_concat(distinct CountryName order by CountryName) into output from DemoTable where
      CountryName like stringValue;
   END
   //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;

使用 call 命令呼叫儲存過程 -

mysql> call searchDemo('U%',@output);
Query OK, 1 row affected, 2 warnings (0.04 sec)

讓我們檢查一下變數 @output 的值 -

mysql> select @output;

會產生以下輸出 -

+---------+
| @output |
+---------+
| UK,US   |
+---------+
1 row in set (0.00 sec)

更新於:2019 年 8 月 22 日

215 次瀏覽

開創你的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.