在姓氏记录的基础上在MySQL查询中添加列数?
让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100), LastName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(FirstName,LastName) values('David','Miller'); mysql> insert into DemoTable(FirstName,LastName) values('Carol','Miller'); mysql> insert into DemoTable(FirstName,LastName) values('John','Doe');
使用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”出现两次:
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)