- 创建表:
create table if not exists `tableName`(
`id` int auto_increment,-- 自增
`title` varchar(100),
primary key (`id`) --主键
);
- 删除表:
不需要表:drop table `tableName`
;
删除表中全部数据:truncate table `tableName`
;
删除表中某条数据:delete from `tableName` where 1=1
; - 插入数据:
insert into `tableName`(`id`) values(1),(2)
; - 查询语句:
select * from `tableName` where 1=1;
- 更新语句:
update `tableName` set `title` = 'title' where `id` = 1;
- 删除语句:
delete from tableName where id = 2;
- like: 用于where子语句,
%XX,以XX结尾;
XX%,以XX开头
%XX%,包含XX
select * from table where name like %a%;
- SQL UNION 默认不重复,允许重复使用 UNION ALL
select name from table1 union select name from table2
- 排序 order by
asc 升序, 默认项
desc 倒序,降序
select name from table1 where id = 1 order by id desc
- group by
SELECT `name` ,COUNT(1) FROM employee_tbl GROUP BY `name`;
- WITH ROLLUP 跟列排序有关,(a,b,c)产生(a,b,c)、(a,b)、(a)三种层次聚合
SELECT COALESCE( `name`, '总数') as singin_name, SUM(singin) as singin_count FROM table1 GROUP BY `name` WITH ROLLUP;
//coalesce(a,b,c) a==null则选择b,b==null则选择c
此处还有cube,多维度聚合,(a,b,c)产生(a,b,c)、(a,b)、(a,c)、(a)、(b,c)、(b)、(c) - 连接
- INNER JOIN 可省略为JOIN 交集
- LEFT JOIN 读取左表所有,右侧没有则显示NULL
- RIGHT JOIN 读取右表所有,左侧没有则显示NULL
SELECT * FROM table1 a JOIN table2b ON a.id = b.id
- NULL判断必须使用IS NULL 或者IS NOT NULL或 <=> 两者都为null返回true
还可以利用ISNULL(exp)
select * from table1 where NOT ISNULL(name)
等同于
select * from table1 where name is not null
- 正则表达式:跟mysql无关,多用于输入验证,或爬虫匹配
- ^a 匹配以a开头的字符串
- b$ 匹配以b结尾的字符串
- . 匹配出\r以外的任意字符
- [abcd] 匹配abcd中的任意字符
- [^abcd] 匹配除此之外的任意字符
- a|b|c 匹配aOR b OR c
- * 匹配0次或以上 等价{0,}
- + 匹配至少一次 等价{1,}
- {n} 匹配n次,n >=0
- {n,m} 匹配至少n次,最多m次
- 事务:
- BEGIN 开始一个事务
- ROLLBACK 事务回滚
- COMMIT 事务确认
默认自动提交,设置SET AUTOCOMMIT=0
禁止自动提交
- alter
- 删除字段
alter table table1 drop id;
- 新增字段
alter table table1 add id INT;
- 修改字段
alter table table1 modify id char(10);
alter table table1 change id id char(10);
alter table table1 change id ids INT;
- 修改字段默认值
alter table table1 modify name varchar(100) not null default 'a';
alter table table1 alter name drop default;
- 修改表名:
alter table table1 rename to table2;
- 删除字段
- 索引
- 创建索引
create index indexName on table1(name(10));
- 添加索引
alter table table1 add index indexName(name);
- 删除索引
drop index indexName on table1;
- 创建唯一索引
create unique index indexName on table1(name(10));
- 创建索引
- 临时表 只存在于当前会话中
CREATE TEMPORARY TABLE tableTemp;
- 复制表
- 只复制表结构
create table newTable like oldTable;
- 复制表结构及数据
create table newTable select * from oldTable;
- 只复制表结构
Mysql 基础语法总结
猜你喜欢
转载自blog.csdn.net/vadonmo/article/details/79389477
今日推荐
周排行