Mysql的Rownum使用示例
1,显示当前查询结果的行号SELECT@rownum := @rownum +1 AS rownum,e.*FROM(SELECT@rownum := 0) r,employee e 显示结果如下:2,按部门分组并按年龄降序排序并显示排名SELECTIF(@dept = e.deptNo,@rank := @rank +1,@rank := 1) A...
·
1,显示当前查询结果的行号
SELECT
@rownum := @rownum +1 AS rownum,
e.*
FROM
(SELECT
@rownum := 0) r,
employee e
显示结果如下:
2,按部门分组并按年龄降序排序并显示排名
SELECT
IF(@dept = e.deptNo,@rank := @rank +1,@rank := 1) AS rank,
@dept := e.deptNo,
e.*
FROM
(SELECT
@deptno := NULL,@rank := 0) r,
employee e
ORDER BY e.deptNo ASC,e.age DESC
查询结果如下
3,批量插入值,并保证值自增(主键列没有自增序列)
INSERT INTO employee(id,NAME,age,deptNo)
SELECT
t.id,t.name,t.age,t.deptNo
FROM (
SELECT
@rownum := @rownum + 1,
(SELECT MAX(e1.id) FROM employee e1) + @rownum AS id,
CONCAT('姓名', @ROWNUM) AS NAME,
@rownum * 10 AS age,
30 AS deptNo
FROM
(SELECT
@rownum := 0) r,
employee e
WHERE e.deptno = 20
) t
插入后,查询结果如下
更多推荐
已为社区贡献1条内容
所有评论(0)