SQL INSERT语句的时候,要避免 指定那个自增的字段.否则会发生主键的冲突。
通过 ALTER TABLE语句 可以修改 自增的数值, 但是只能增加,不能减少。
TRUNCATE TABLE 语句,会将自增ID重置为零。
mysql> CREATE TABLE test_create_tab2 (
-> id INT AUTO_INCREMENT,
-> val VARCHAR(10),
-> PRIMARY KEY (id)
-> )
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id')
Query OK, 1 row affected (0.03 sec)
mysql> select last_insert_id() as id
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
mysql> INSERT INTO test_create_tab2(val) VALUES ('NO id 2')
Query OK, 1 row affected (0.03 sec)
mysql> select last_insert_id() as id
+----+
| id |
+----+
| 2 |
+----+
1 row in set (0.00 sec)
mysql> select * from test_create_tab2
+----+---------+
| id | val |
+----+---------+
| 1 | NO id |
| 2 | NO id 2 |
+----+---------+
2 rows in set (0.00 sec)
需要用row_number来给分组添加序号。
1、创建测试表,插入数据:
create table test(sid int,sname varchar(20),sclass varchar(20),score int) insert into test values (1,'张三','一年一班',100)insert into test values (2,'李四','一年一班',78)insert into test values (3,'王五','一年一班',67)insert into test values (4,'赵六','一年一班',87)insert into test values (5,'badkano','一年二班',98)insert into test values (6,'百度知道团长','一年二班',99)insert into test values (7,'du小小动','一年二班',99)insert into test values (8,'刘备','一年三班',56)insert into test values (9,'张飞','一年三班',67)insert into test values (10,'关羽','一年三班',76)
2、要求按照班级总分给出班级排名(即序号),执行语句:
1select row_number() over (order by score desc) 排名,sclass 班级,score 总分 from (select sclass,SUM(score) score from test group by sclass) t3、查询结果:
方法一、直接在程序中实现,推荐方法二、数据库
select @x:=ifnull(@x,0)+1 as rownum, * from tbl
rownum就是你要的编号
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)