MySQL 查询来查找两个列中出现次数?
使用 MySQL GROUP_BY 来查找两列中出现的次数。我们先创建一个表 -
mysql> create table DemoTable -> ( -> Name1 varchar(20), -> Name2 varchar(20) -> ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('John','Adam'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Chris','David'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Robert','Mike'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('David','Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Mike','Robert'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+--------+--------+ | Name1 | Name2 | +--------+--------+ | John | Adam | | Chris | David | | Robert | Mike | | David | Chris | | Mike | Robert | +--------+--------+ 5 rows in set (0.00 sec)
以下是对两列中出现次数的查询 -
mysql> select greatest(Name1,Name2),least(Name1,Name2),count(*) as Occurrences from DemoTable -> group by greatest(Name1,Name2),least(Name1,Name2);
这将产生以下输出 -
+-----------------------+--------------------+-------------+ | greatest(Name1,Name2) | least(Name1,Name2) | Occurrences | +-----------------------+--------------------+-------------+ | John | Adam | 1 | | David | Chris | 2 | | Robert | Mike | 2 | +-----------------------+--------------------+-------------+ 3 rows in set (0.02 sec)
广告