数据库常用的sql语句语法

数据库中常用sql语句总结:
连接本机服务器,登录服务器:

mysql -uroot -p
[输入密码root]

查看表结构:

desc user(表名);

退出登录、断开连接

exit;
quit;
\q

建库

-- 删除db1库
drop database if exists db1;
-- 重新创建db1库
create database db1
charset utf8;
-- 查看、进入db1库
show databases;
use db1;

建表

-- 删除stu学生表
drop table if exists stu;
-- 创建stu表
create table stu (
   id int,
   name varchar(20),
   gender char(1),
   birthday date
);
-- 查看表结构
desc stu;

插入数据

insert into stu values(6,'张三','男','1996-8-4');

指定字段id,name

 insert into stu(id, name) values(7, '李四');
 insert into stu(id, name) values(8,'王五'), (9,'赵六'), (10,'钱七');

*– 中文
– 先告诉服务器,客户端是什么编码
– 连接断开之前,服务器可以记住这个编码
set names gbk;*

update 更新、修改数据

 update stu set gender='女',birthday='1998-8-4' where id=7;

delete 删除数据

-- 删除 id>8 的数据
delete from stu where id>8;

select 查询

select * from stu 查询所有字段
select name, gender from stu 查询指定的字段

where子句
设置过滤条件

=      等值过滤
<>     不等过滤
> >= < <=    
between 小 and 大   >= 小 并且 <= 大
in(7,2,9,4)    在指定的一组值中取值
is nullnull
is not null   不是null
like    字符串模糊匹配 % 通配多个字符 _ 通配单个字符
           \%(转译)
           \_(转译)
            \\(转译)
not  not between and || not in(...) || is not null not like
and 并且
or  或者

– 员工id是122
select id,fname,sal,dept_id from emps where id=122;
– 部门编号dept_id是30
select id,fname,sal,dept_id from emps where dept_id=30;
– 工作岗位代码job_id是’IT_PROG’
select id,fname,sal,dept_id,job_id from emps where job_id=’IT_PROG’;
– 部门编号dept_id 不是 50
select id,fname,sal,dept_id from emps where dept_id<>50;
– 工资sal>5000
select id,fname,sal,dept_id from emps where sal>5000;

– 工资范围 [5000, 8000]
select id,fname,sal,dept_idfrom emps where sal>=5000 and sal<=8000;

select id,fname,sal,dept_id from emps where sal between 5000 and 8000;

– id是 120,122,100,150
select id,fname,sal,dept_id from emps where id in(120,122,100,150);

select id,fname,sal,dept_id from emps where id=120 or id=122 or id=100 or id=150;
– 没有部门的员工,dept_id 是 null
select id,fname,sal,dept_id from emps where dept_id is null;
– 有提成的员工,com_pct 不是null
select id,fname,sal,dept_id from emps where com_pct is not null;
– fname 中包含 en
select id,fname,sal,dept_id from emps where fname like ‘%en%’;
– fname 第3、4个字符是en
select id,fname,sal,dept_id from emps where fname like ‘__en%’;
**distinct 去除重复
select distinct a from ...去除a字段重复值

select distinct a,b from ... 去除a,b字段组合的重复值

order by 子句
**order by a 按a字段升序排列
order by a,b 按a字段升序排列,a相同,再按b字段升序排列
asc 升序(默认)
desc 降序**

order by a desc
order by a desc, b asc
order by a desc, b desc

单引号 字符串内容中的单引号,用两个单引号转义

'I'm Abc'
'I''m Abc'
insert into stu(id,name) values(6433, 'I''m Xxx');

数字函数

ceil(数字) 向上取整到个位
floor(数字) 向下取整到个位
round(数字, 2) 四舍五入到小数点2位
truncate(数字, 2) 舍弃到小数点2位
rand() 随机数[0, 1)

日期函数

now() 当前日期时间
curdate() 当前日期
curtime() 当前时间
extract(字段 from 日期) 抽取指定字段的值
date_add(日期, interval 字段 值) 在指定字段上加一个值
datediff(日期1, 日期2) 两个日期之间相差的天数

group by 子句,分组求多行函数

按指定字段中相同的值进行分组
分组后分别求多行函数
分组字段,可以查询
group by aa字段相同值分组
group by a,b 按a,b组合的相同值分组

猜你喜欢

转载自blog.csdn.net/qq1083273166/article/details/81510056