MySQL grammar notes (for personal use)

database operation

create database 数据库名;
drop database 数据库名;

table operation

-- 建表
create table userinfo(
id int(10) primary key  auto_increment, -- primary key关键字   auto_increment自增 
username varchar(20) unique,  --unique唯一
status varchar(20)
);


-- 删除主键(primary key)
alter table userinfo drop primary key;

-- 删除唯一(unique)
alter table userinfo drop key username;

-- 删除自增
alter table userinfo modify id int;
-- 删表
drop table userinfo;

-- 备份表
create table 表名 as (select * from 表名);

-- 改表名
rename 表名 to 表名;

The fields in the table are added, deleted, and changed/modified. Syntax
: alter table table name add | change/modify | drop field name type constraint;

alter table userinfo add status int;

alter table userinfo drop email;

alter table userinfo change username login_name varchar(20);
alter table userinfo modify username varchar(16); #modify不可以用来修改字段名
alter table userinfo change username username int;
alter table userinfo change username my_username  varchar(16); #同时修改字段名和数据类型
alter table userinfo modify `status` int first;
alter table userinfo modify `status` int after login_name;

operation table

The complete syntax of the query:
select field|expression from table name|view|result set
[where condition]
[group by grouping]
[retrieval after having grouping]
[order by sorting]
[limit limit result]

-- 最低工资大于等于100,用户ID在75,702,5606,804,818中,管理员姓名第二个字母是z,工资倒序排列
select 
	distinct a.name 名字去重,
	o.order_id,
	a.user_id,
	o.price 价格,
	if(o.price = 1999,'工资高','工资低'), -- ifnull(price ,0) 判断price 列是否是null,如果是null,则赋值为0
	avg(o.price ) + 0.5 AS 平均数 
from
	sxo_answer a
	inner join 
	sxo_order_detail o 
	on 
	a.user_id = o.user_id 
where -- where后面不可以接聚合函数,where单独使用使用
	o.user_id in ( 75, 702, 5606, 804, 818 ) 
	and 
	a.name like '_z%' 
group by
	o.price 
having -- having 后面可以接聚合函数,having搭配group by使用
	min(o.price )>= 100 
order by
	o.order_id desc 
	limit 
	2, 3;-- limit是从第3行开始,往后取3行(取3到6行)
-- limit m,n m:开始的位置,索引值从0开始 n:取值的长度(个数)

-- 插入
insert into sxo_answer(id,user_id,name) values(1,1,'abc'),(2,2,'edf');

-- 修改
update sxo_answer set name='abc' where id=1;

-- 删除
delete from sxo_answer where id=1;

-- 清空
truncate table sxo_answer;

-- 删表
drop table sxo_answer;

min() -- 最小值
max() -- 最大值
avg() -- 平均值
sum() -- 总计
count() -- 统计行数
round() -- 四舍五入

表名 left join 表名 on 条件
表名 right join 表名 on 条件

Note: What is the difference between delete and truncate 1: delete deletes line by line, truncate clears files at
the file level place

Guess you like

Origin blog.csdn.net/qq_36562656/article/details/127671752