使用 MySQL 查找重复项并显示在单行中
为此,可以使用 GROUP_CONCAT() 以及 GROUP BY 子句。两者都用于对重复项进行组合并显示在单行中。我们首先创建一个表 -
mysql> create table DemoTable ( StudentFavouriteSubject varchar(40), StudentName varchar(40) ) ; Query OK, 0 rows affected (0.75 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('MySQL','Chris'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('MongoDB','Bob'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('MySQL','Sam'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Java','Mike'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('C','Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('MongoDB','John'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将生成以下输出 -
+-------------------------+-------------+ | StudentFavouriteSubject | StudentName | +-------------------------+-------------+ | MySQL | Chris | | MongoDB | Bob | | MySQL | Sam | | Java | Mike | | C | Carol | | MongoDB | John | +-------------------------+-------------+ 6 rows in set (0.00 sec)
以下查询用于查找重复项并显示在单行中 -
mysql> select group_concat(StudentName),StudentFavouriteSubject from DemoTable group by StudentFavouriteSubject;
这将生成以下输出 -
+---------------------------+-------------------------+ | group_concat(StudentName) | StudentFavouriteSubject | +---------------------------+-------------------------+ | Carol | C | | Mike | Java | | Bob,John | MongoDB | | Chris,Sam | MySQL | +---------------------------+-------------------------+ 4 rows in set (0.00 sec)
广告