Mysql 基础语法总结

  1. 创建表:

    create table if not exists `tableName`(
    `id` int auto_increment,-- 自增
    `title` varchar(100),
    primary key (`id`) --主键
    );
  2. 删除表:
    不需要表:drop table `tableName`;
    删除表中全部数据:truncate table `tableName`;
    删除表中某条数据:delete from `tableName` where 1=1;
  3. 插入数据:
    insert into `tableName`(`id`) values(1),(2);
  4. 查询语句:
    select * from `tableName` where 1=1;
  5. 更新语句:
    update `tableName` set `title` = 'title' where `id` = 1;
  6. 删除语句:
    delete from tableName where id = 2;
  7. like: 用于where子语句,
    %XX,以XX结尾;
    XX%,以XX开头
    %XX%,包含XX
    select * from table where name like %a%;
  8. SQL UNION 默认不重复,允许重复使用 UNION ALL
    select name from table1 union select name from table2
  9. 排序 order by
    asc 升序, 默认项
    desc 倒序,降序
    select name from table1 where id = 1 order by id desc
  10. group by
    SELECT `name` ,COUNT(1) FROM employee_tbl GROUP BY `name`;
  11. 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)
  12. 连接
    1. INNER JOIN 可省略为JOIN 交集
    2. LEFT JOIN 读取左表所有,右侧没有则显示NULL
    3. RIGHT JOIN 读取右表所有,左侧没有则显示NULL
      SELECT * FROM table1 a JOIN table2b ON a.id = b.id
  13. 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
  14. 正则表达式:跟mysql无关,多用于输入验证,或爬虫匹配
    1. ^a 匹配以a开头的字符串
    2. b$ 匹配以b结尾的字符串
    3. . 匹配出\r以外的任意字符
    4. [abcd] 匹配abcd中的任意字符
    5. [^abcd] 匹配除此之外的任意字符
    6. a|b|c 匹配aOR b OR c
    7. * 匹配0次或以上 等价{0,}
    8. + 匹配至少一次 等价{1,}
    9. {n} 匹配n次,n >=0
    10. {n,m} 匹配至少n次,最多m次
  15. 事务:
    1. BEGIN 开始一个事务
    2. ROLLBACK 事务回滚
    3. COMMIT 事务确认
      默认自动提交,设置SET AUTOCOMMIT=0禁止自动提交
  16. alter
    1. 删除字段 alter table table1 drop id;
    2. 新增字段 alter table table1 add id INT;
    3. 修改字段
      1. alter table table1 modify id char(10);
      2. alter table table1 change id id char(10);
      3. alter table table1 change id ids INT;
    4. 修改字段默认值
      1. alter table table1 modify name varchar(100) not null default 'a';
      2. alter table table1 alter name drop default;
    5. 修改表名:alter table table1 rename to table2;
  17. 索引
    1. 创建索引 create index indexName on table1(name(10));
    2. 添加索引 alter table table1 add index indexName(name);
    3. 删除索引 drop index indexName on table1;
    4. 创建唯一索引 create unique index indexName on table1(name(10));
  18. 临时表 只存在于当前会话中 CREATE TEMPORARY TABLE tableTemp;
  19. 复制表
    1. 只复制表结构create table newTable like oldTable;
    2. 复制表结构及数据create table newTable select * from oldTable;

猜你喜欢

转载自blog.csdn.net/vadonmo/article/details/79389477