如何在 MySQL 中将结果显示在一行中?
为此,你可以使用 group_concat()。我们先创建一个表 -
mysql> create table DemoTable1507 -> ( -> Name varchar(20), -> PaperSet int -> ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable1507 values('Chris',111); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable1507 values('David',112); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable1507 values('Mike',111); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1507 values('Bob',113); Query OK, 1 row affected (0.14 sec)
使用 select 语句从表中显示所有记录 -
mysql> select * from DemoTable1507;
这将生成以下输出 -
+-------+----------+ | Name | PaperSet | +-------+----------+ | Chris | 111 | | David | 112 | | Mike | 111 | | Bob | 113 | +-------+----------+ 4 rows in set (0.00 sec)
以下是对 MySQL 中仅显示一行结果的查询 -
mysql> select group_concat(Name order by Name desc separator ':') -> from DemoTable1507 -> where PaperSet=111;
这将生成以下输出 -
+-----------------------------------------------------+ | group_concat(Name order by Name desc separator ':') | +-----------------------------------------------------+ | Mike:Chris | +-----------------------------------------------------+ 1 row in set (0.00 sec)
广告