MySQL的基础语法-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) anull则选择b,bnull则选择c
此处还有cube,多维度聚合,(a,b,c)产生(a,b,c)、(a,b)、(a,c)、(a)、(b,c)、(b)、©
连接
- 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;
批量更新uuid
UPDATE mt_note SET uuid =UUID();
如果想去掉-需要先设置为36位,再批量更新替换掉-;直接使用REPLACE,会使所有uuid一样。
UPDATE mt_note SET uuid =UUID();
UPDATE mt_note SET uuid = REPLACE(uuid,'-','');