1、求平均数,且结果保留小数点后面3位(3位之后四舍五入)
CAST(AVG(score) AS DECIMAL(10,3));
- CAST()函数,把一个字段转成另一个字段。其语法为:CAST(字段名 AS 转换的类型 )
CHAR[(N)] 字符型
DATE 日期型
DATETIME 日期和时间型
DECIMAL float型
SIGNED int
TIME 时间型
DECIMAL
(P,D)
P
是表示有效数字数的精度。 P
范围为1〜65
。 D
是表示小数点后的位数。 D
的范围是0
~30
。MySQL要求D
小于或等于(<=
)P
。
例如:DECIMAL(6,2); 则该列最多可存储六位数字(小数点不算),小数位占2位。
2、批量插入数据
eg:【对于表actor批量插入如下数据(不能有2条insert语句哦!)】
insert into
actor(actor_id,first_name,last_name,last_update)
values
(1,'PENELOPE','GUINESS','2006-02-15 12:34:33'),
(2,'NICK','WAHLBERG','2006-02-15 12:34:33');
#values后虽然是两行数据,但是外边不能加括号
#Datetime数据类型,数据存储的话要加单引号
3、replace()函数的使用
replace(列名,原数据,替换的新数据);
- 更新替换
#将id=5以及emp_no=10001的行数据替换成id=5以及emp_no=10005,其他数据保持不变
#使用replace实现,直接使用update会报错。
update titles_test
set emp_no=replace(emp_no,'10001','10005')
where id=5;
另外还有一种插入替换,请参考以下博客:
博客链接:https://blog.youkuaiyun.com/bingguang1993/article/details/80592579/
4、修改表名
rename table [旧表名] to [新表名];
#eg:将titles_test表名修改为titles_2017。
rename table titles_test to titles_2017;
5、插入数据(如果数据存在请忽略)
#对于表actor插入如下数据,如果数据已经存在请忽略。
insert ignore into
actor(actor_id,first_name,last_name,last_update)
values('3','ED','CHASE','2006-02-15 12:34:33');
6、新增列,并添加默认值
#新增加一列名字为create_date, 类型为datetime, NOT NULL,默认值为'2020-10-01 00:00:00'
alter table actor
add column
create_date datetime not null default '2020-10-01 00:00:00';
7、添加索引
#添加PRIMARY KEY(主键索引)
alter table 表名 add primary key(列名);
#添加UNIQUE(唯一索引)
alter table 表名 add unique 索引名(列名);
#添加普通索引
alter table 表名 add index 索引名(列名);
#添加全文索引
alter table 表名 add fulltext(列名);
#添加多列索引
alter table 表名 add index 索引名(列名1,列名2,列名3);
8、通过强制索引查询
语法(MySQL):
SELECT * FROM table_name FORCE INDEX(index_name) WHERE conditions;