Mysql常用语法总结
Mysql常用语法总结如下:
#连接mysql数据库(Dos下面)
mysql -u root -p 123
#创建数据库
create database myschool;
#创建表
drop table student
create table student
(
id int comment '编号',
name CHAR(10) comment '姓名'
)charset =utf8
drop table if exists student;
#修改表名
alter table student rename students;
#添加字段
alter table students add phone int ;
#修改字段
alter table students change phone phones int ;
select * from students;
#删除字段
alter table students drop phones;
#添加主键
alter table student
add constraint p_id primary key student (id);
#添加外键
alter table student
add constraint fk_gradeid foreign key (gradeid) references grade (gradeid);
select * from student
#插入数据(单条)
insert into student (id,name) values(1,'张三');
#插入多条数据
insert into student values(5,'李四1'),(6,'王五1'),(7,'赵六1'),(8,'李四2'),(9,'王五2'),(10,'赵六2');
#将查询结果插入到新表中(第一种)
#新表必须提前创建
create table students
(
id int ,
name CHAR(10)
)
insert into students(id,name) select * from student
#将查询结果插入到新表中(第二种)
#新表无需提前创建
create table studentss (select * from student);
#修改数据
update student set name = '李四' where id = 1
#删除数据
delete from student where id = 1;
#truncate语句删除后讲重置自增列,表结构及其字段、约束、索引保持不变,执行速度比delete快
truncate table student;
#分页查询
select * from student
where id in(1,2,3,4,5,6,7,8,9)
group by name
order by id desc
limit 2, 5
###########聚合函数###########
#平均值
select AVG(id) from student;
#总记录数
select COUNT(1) from student;
#求和
select SUM(id) from student;
#求最大值
select MAX(id) from student;
#求最小值
select MIN(id) from student;
##################常用函数#################
# 字符串连接
select CONCAT('my','s','ql')
#字符串替换
SELECT INSERT(
'这是SQL Server数据库',
3,10,'MySQL');
# 将字符串转为小写
SELECT LOWER('MySQL');
#将字符串转为大写
SELECT UPPER('MySQL');
#字符串截取
SELECT SUBSTRING(
'JavaMySQLOracle',5,5);
###################日期函数#################
#获取当前日期
SELECT CURDATE();
#获取当前时间
SELECT CURTIME();
#获取当前日期和时间
SELECT NOW();
#返回日期date为一年中的第几周
SELECT WEEK(NOW());
#返回日期date的年份
SELECT YEAR(NOW());
#返回时间time的小时值
SELECT HOUR(NOW());
#返回时间time的分钟值
SELECT MINUTE(NOW());
#返回日期参数date1和date2之间相隔的天数
SELECT DATEDIFF(NOW(),
'2008-8-8');
#计算日期参数date加上n天后的日期
SELECT ADDDATE(NOW(),5);
###############数学函数####################
#返回大于或等于数值x的最小整数
SELECT CEIL(2.3)
#返回小于或等于数值x的最大整数
SELECT FLOOR(2.3)
#返回0~1间的随机数
SELECT RAND()
#################子查询###################
#查看年龄比李斯文小的学生,要求显示这些学生的信息
select * from student where borndate>
(select borndate from student where student name ='李斯文').
#创建一个年级表
create table grade
(
id int ,
name varchar(50)
)
#student表与grade表进行关联
select * from student s join grade g on s.gradeid = g.gradeid
select * from student s,grade g where s.gradeid = g.gradeid
#in子句
select * from student where id in (1,2,3,4)
#not in子句
select * from student where id not in (1,4)