鉴于
+----+----------+
| id | lastname |
+----+----------+
| 1 | aaa |
| 2 | bbb |
| 3 | ccc |
+----+----------+
3 rows in set (0.00 sec)
你的第一个查询到MySQL的指令在整个集
MariaDB [sandbox]> select id = count(*) as id, lastname
-> from users;
+------+----------+
| id | lastname |
+------+----------+
| 0 | aaa |
+------+----------+
1 row in set (0.00 sec)
显然,这不返回最后一个ID或正确的计数来计算。
select id, lastname , count(*)
from users;
+------+----------+----------+
| id | lastname | count(*) |
+------+----------+----------+
| 1 | aaa | 3 |
+------+----------+----------+
1 row in set (0.00 sec)
而且id和lastname是不确定的。
你的第二个查询返回笛卡尔积
select id = count2, lastname, count2
-> from users, (select count(*) as count2 from users) seat2
-> ;
+-------------+----------+--------+
| id = count2 | lastname | count2 |
+-------------+----------+--------+
| 0 | aaa | 3 |
| 0 | bbb | 3 |
| 1 | ccc | 3 |
+-------------+----------+--------+
3 rows in set (0.00 sec)
再次不识别匹配的计数的ID ..
假设ID是一个数字,增量以某种方式方式,也确实找到最后一个ID为
MariaDB [sandbox]> select id,lastname
-> from users
-> where id = (select count(*) from users);
+----+----------+
| id | lastname |
+----+----------+
| 3 | ccc |
+----+----------+
1 row in set (0.00 sec)
但是,这是危险的 - 如果id为AUTO_INCREMENT再行数可能不匹配,因为这样AU的id to_increment被处理(它可以被重写,在重复键上插入更新等。) 一个更安全的方法是
MariaDB [sandbox]> select id,lastname
-> from users
-> where id = (select max(id) from users);
+----+----------+
| id | lastname |
+----+----------+
| 3 | ccc |
+----+----------+
1 row in set (0.00 sec)
你想达到什么目的? – user1506104
为什么它只给你一行,请点击这里查看:http://www.mysqltutorial.org/mysql-count – user1506104
您应该在教程 –