MySQL查询从两列中查找出现的次数?
使用MySQLGROUP_BY从两列中查找出现的次数。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Name1 varchar(20), -> Name2 varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('John','Adam'); mysql> insert into DemoTable values('Chris','David'); mysql> insert into DemoTable values('Robert','Mike'); mysql> insert into DemoTable values('David','Chris'); mysql> insert into DemoTable values('Mike','Robert');
使用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)