在 MySQL 查询中基于姓名称记录添加计数列?
我们首先创建一个表——
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100), LastName varchar(100) ); Query OK, 0 rows affected (1.00 sec)
使用 insert 命令在表中插入一些记录——
mysql> insert into DemoTable(FirstName,LastName) values('David','Miller'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable(FirstName,LastName) values('Carol','Miller'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable(FirstName,LastName) values('John','Doe'); Query OK, 1 row affected (0.21 sec)
使用 select 语句从表中显示所有记录——
mysql> select *from DemoTable;
这将产生以下输出——
+----+-----------+----------+ | Id | FirstName | LastName | +----+-----------+----------+ | 1 | David | Miller | | 2 | Carol | Miller | | 3 | John | Doe | +----+-----------+----------+ 3 rows in set (0.00 sec)
以下是为姓名称记录添加计数列的查询,例如“Miller”出现 2 次:
mysql> select Id, FirstName, LastName,Count from DemoTable tbl1 JOIN (select count(*) as Count, LastName from DemoTable GROUP BY LastName) tbl2 using(LastName);
这将产生以下输出——
+----+-----------+----------+-------+ | Id | FirstName | LastName | Count | +----+-----------+----------+-------+ | 1 | David | Miller | 2 | | 2 | Carol | Miller | 2 | | 3 | John | Doe | 1 | +----+-----------+----------+-------+ 3 rows in set (0.00 sec)
广告