在 MySQL GROUP_CONCAT 中实现编号
首先,我们创建一个表格 −
mysql> create table DemoTable1627 -> ( -> FirstName varchar(20), -> LastName varchar(20) -> ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令向表中插入一些记录。
mysql> insert into DemoTable1627 values('John','Smith'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1627 values('John','Doe'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1627 values('Adam','Smith'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1627 values('Carol','Taylor'); Query OK, 1 row affected (0.08 sec)
使用 select 语句从表中显示所有记录 −
mysql> select * from DemoTable1627;
这将产生以下输出 −
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Smith | | John | Doe | | Adam | Smith | | Carol | Taylor | +-----------+----------+ 4 rows in set (0.00 sec)
以下是实现 group_concat() 编号的查询 −
mysql> select LastName, -> group_concat( -> concat(@j := if (@p = LastName, @j + 1, if(@p := LastName,1,1)), '.', FirstName) -> separator ', ') FirstName -> from DemoTable1627 -> group by LastName;
这将产生以下输出 −
+----------+----------------+ | LastName | FirstName | +----------+----------------+ | Doe | 1.John | | Smith | 1.John, 2.Adam | | Taylor | 1.Carol | +----------+----------------+ 3 rows in set (0.09 sec)
广告