测试数据准备:
create table student(
stu_id int primary key,
stu_name varchar(20),
chinese_score int,
math_score int);
insert into student values(1,'Tom',90,80);
insert into student values(2,'Mike',70,90);
insert into student values(3,'Jane',80,60);
MySQL添加值固定列
select 固定值 as 列名 from ...
示例:
select * ,'男' as sex from student;//此时sex变为字符串类型(varchar),MySQL自动识别类型
select * ,1 as sex from student;//此时sex为int类型
MySQL添加值自动增长列
写法一:
set @rownum=0;
select @rownum:=@rownum+1 as num ,student.* from student;
写法二:
select @rownum:=@rownum+1 as num ,student.* from student,(select @rownum=0) t;
注意student.* 不能写成 * ,注意赋值是 ‘:=’
拓展:关于hive中的查询自增列
方式一:使用row_number() over() 实现
原表形式:
添加自增列语句:
select row_number() as num ,dept.* from dept;
效果:
若按某字段进行排序,可将排序字段over中
select row_number() over (order by dept.deptno) as num ,dept.* from dept;
效果:
方式二:用UDFRowSequence生成代理键(未实践)