注释

  1. #
  2. /**/
  3. --

数据库创建与适用

  1. create database test;
  2. use test;

创建表

  1. create table mytable(
  2. id INT NOT NULL AUTO_INCREMENT,
  3. col1 INT NOT NULL DEFAULT 1,
  4. col2 VARCHAR(45) NULL,
  5. col3 DATE NULL,
  6. PRIMARY KEY(`id`)
  7. );


修改表

  • 添加列

    1. alter table mytable add newcol char(20);
  • 删除列

    1. alter table mytable drop column newcol;
  • 删除表

    1. drop table mytable;


    插入

  • 普通

    1. insert into mytable(col1,col2) values(val1,val2);
  • 插入检索数据

    1. insert into mytable1(col1,col2) select col1,col2 from mytable2;
  • 将检索内容插入一个新表

    1. create table newtable as select * from mytable;

更新

  1. update mytable
  2. set col=val
  3. where id=1;

删除

  1. delete from mytable where id=1;

清空

  1. truncate table mytable;

查询

  • distinct

    • 作用于所有列
      1. select distinct col1,col2 from mytable;
  • limit

    • 起始行(从0开始)
    • 总行数 ```sql select from mytable limit 5; select from mytable limit 0,5;

select * from mytable limit 2,3;

  1. <a name="j5uEh"></a>
  2. ### <br />
  3. <a name="TH3sA"></a>
  4. ### 排序
  5. - asc
  6. - desc
  7. ```sql
  8. select * from mytable
  9. order by col1 desc,col2 asc;

过滤

  • =, <, >, <>, !=, <=, !>, >=, !<, between, is null
  • 优先处理 and

通配符

  • %:匹配>=0个任意字符
  • _:匹配1个任意字符
  • []:匹配集合内的字符,或连接
  • ^:否定
  • 在开头处匹配会非常慢 ```sql select * from mytable where col like ‘[^AB]%’;

匹配不以A和B开头的任意文本

  1. <a name="fa9ID"></a>
  2. ### <br />
  3. <a name="S2ju4"></a>
  4. ### 计算字段
  5. - 取别名
  6. ```sql
  7. select col1*col2 as alias
  8. from mytable;
  • concat:连接时去掉空格填充
  • trim:去除首尾空格

    1. select concat(trim(col1),'(',trim(col2),')') as concat_col
    2. from mytable;

    函数

  • avg:忽略NULL行

  • count:结合distinct,汇总不同的值
  • max
  • min
  • sum

    1. select avg(distinct col1) as avg_col from mytable;

    文本处理

  • left:LEFT(ARG,LENGTH),返回ARG最左边的LENGTH个字符串,ARG可以是CHAR或BINARY STRING。

  • right:RIGHT(ARG,LENGTH) ,返回ARG最右边的LENGTH个字符串
  • lower:转换为小写字符
  • upper:转换为大写字符
  • ltrim:去除左边空格
  • rtrim:去除右边空格
  • length:长度
  • soundex:转换为语音值

分组

  • NULL的行单独分为一组
  • 按指定的分组字段进行分组

    1. select col,count(*) as num
    2. from mytable
    3. group by col;
  • 分组后按指定字段进行排序

    1. select col,count(*) as num
    2. from mytable
    3. group by col
    4. order by num;
  • 过滤分组

    1. select col,count(*) as num
    2. from mytable
    3. where col>2
    4. group by col
    5. having num>=2;

    子查询

  • 子查询中只能返回一个字段的数据

  • 可以将子查询的结果作为where语句的过滤条件

    • 检索出客户的订单数量,子查询语句会对第一个查询检索出的每个客户执行一次
      1. select cust_name,(select count(*) from orders where orders.cust_id = customers.cust_id) as orders_num
      2. from customers
      3. order by cust_name;

      连接

  • join … on …

  • 内连接(等值连接):inner join

    1. select A.value,B.value
    2. from tableA as A inner join tableB as B
    3. on A.key = B.key;
  • 自连接(与自身进行内连接)

    • 子查询 ```sql select name from employee where department = (

    select department from employee where name = “Jim”

);

  1. - 自连接
  2. ```sql
  3. select e1.name
  4. from employee as e1 inner join employee as e2
  5. on e1.department = e2.department and e2.name = "Jim";
  • 自然连接

    • 同名列通过等值测试连接起来,同名列可以有多个
    • 自然连接自动连接所有同名列
      1. select A.value, B.value from tableA as A natural join tableB as B;
  • 外连接

    • 保留了没有关联信息的那些行
      1. select Customers.cust_id,Customer.cust_name,Orders.order_id
      2. from Customers left outer join Orders
      3. on Customers.cust_id = Orders.cust_id;

      组合查询

  • union

    • 如果第一个查询返回M行,第二个查询返回N行,那么组合查询的结果一般为M+N行
    • 每个查询必须包含相同的列、表达式和聚集函数
    • 默认去重
    • 保留全部行:union all ```sql select col from mytable where col = 1

union

select col from mytable where col = 2;

  1. <a name="Ot6st"></a>
  2. ###
  3. <a name="KTbSj"></a>
  4. ### 视图
  5. - 视图是**虚表**,**本身不包含数据**,也就不能对其进行索引操作
  6. - 优点
  7. - 简化sql操作
  8. - 设置访问权限,保证数据的安全性
  9. ```sql
  10. create view myview as
  11. select concat(col1,col2) as concat_col,col3*col4 as compute_col
  12. from mytable
  13. where col5 = val;
  14. create view myview as ...

存储过程

  • 对一系列sql操作的批处理
  • 优点
    • 代码封装,保证安全性
    • 代码复用
    • 预先编译性能高
  • 自定义分隔符
  • 参数:int、out、inout
  • 变量赋值:select into 语句
  • 每次只能给一个变量赋值 ```sql delimiter // create procedure myprocedure(out ret int) begin
    1. declare y int;
    select sum(col1) from mytable int y; select y*y into ret; end //

delimiter ;

call myprocedure(@ret); select @ret;

  1. <a name="iS5o9"></a>
  2. ###
  3. <a name="ymYtK"></a>
  4. ### 游标
  5. - 在存储过程中使用游标,对一个结果集进行**移动遍历**
  6. - 需求:对数据集中的**任意行进行浏览和修改**
  7. - 四个步骤
  8. - **声明游标**
  9. - **打开游标**
  10. - **取出数据**
  11. - **关闭游标**
  12. ```sql
  13. delimiter //
  14. create procedure myprocedure(out ret int)
  15. begin
  16. declare done boolean default 0;
  17. declare mycursort cursor for
  18. select col1 from mytable;

二、自测

  1. ##
  2. /**/
  3. create table aaa;
  4. use aaa;
  5. # 自增(AUTO_INCREMENT)、默认值(DEFAULT 1)、非空(NOT NULL)、主键(PRIMARY KEY(`id`))、设置引擎(ENGINE=)、编码方式(DEFAULT CHARSET=)
  6. create table mytable(
  7. id INT NOT NULL AUTO_INCREMENT,
  8. sex INT NOT NULL DEFAULT 1,
  9. name VARCHAR(45),
  10. dt DATE,
  11. PRIMARY KEY(`id`))
  12. ENGINE=MyISAM,DEFAULT CHARSET=utf8;
  13. create table mytable(
  14. id INT NOT NULL AUTO_INCREMENT,
  15. sex INT NOT NULL DEFAULT 1,
  16. name VARCHAR(45),
  17. dt DATE,
  18. PRIMARY KEY(`id`))
  19. ENGINE=INNODB,DEFAULT CHARSET=UTF8;
  20. # 添加列
  21. ALTER TABLE mytable ADD newcol VARCHAR(50);
  22. ALTER TABLE mytable ADD newcol VARCHAR(50);
  23. # 删除列
  24. ALTER TABLE mytable DROP COLUMN sex;
  25. ALTER TABLE mytable DROP COLUMN sex;
  26. ALTER TABLE mytable DROP COLUMN sex;
  27. # 修改字段类型(MODIFY)
  28. ALTER TABLE mytable MODIFY COLUMN name VARCHAR(100) DEFAULT NOT NULL COMMENT '姓名';
  29. ALTER TABLE mytable MODIFY sex VARCHAR(100) DEFAULT '女' COMMENT '性别';
  30. # 修改字段名(CHANGE)
  31. ALTER TABLE mytable CHANGE name nick_name VARCHAR(100) DEFAULT NULL COMMENT '性别';
  32. # 修改表名(RENAME TO)
  33. ALTER TABLE mytable RENAME TO newtable;
  34. # 修改表注视
  35. ALTER TABLE 表名 COMMENT '新注释';
  36. # 在指定位置加入新列(字段)
  37. ALTER TABLE mytable ADD mobile varchar(50) NOT NULL AFTER name;
  38. # 删除字段
  39. ALTER TABLE mytable DROP COLUMN name;
  40. DROP TABLE mytable;
  41. INSERT INTO mytable(col1,col2) VALUES(val1,val2);
  42. INSERT INTO mytable1(col1,col2) SELECT col1,col2 FROM mytable2;
  43. INSERT INTO mytable1(col1,col2) SELECT col1,col2 FROM mytable2;
  44. CREATE TABLE newtable AS SELECT * FROM mytable;
  45. CREATE TABLE tt as SELECT * from mytable;
  46. # 更新
  47. UPDATE mytable SET age = 10 WHERE id=1
  48. UPDATE mytable SET age=10 WHERE id=2
  49. # 删除
  50. DELETE FROM mytable WHERE id=1;
  51. DELETE FROM mytable WHERE id=1;
  52. # 清空表
  53. TRUNCATE TABLE mytable;
  54. # 查询
  55. SELECT DISTINCT col1,col2 FROM mytable;
  56. SELECT DISTINCT col1,col2 FROM mytable;
  57. SELECT * FROM mytable LIMIT 5;
  58. SELECT * FROM mytable LIMIT 0,5;
  59. SELECT * FROM mytable LIMIT 2,3;
  60. # 排序
  61. SELECT * FROM mytable order by age desc,weight asc;
  62. # 过滤
  63. select * from mytable where col is NULL;
  64. select * from mytable where age = 18;
  65. -- <> != <= !> BETWEEN A AND B
  66. select * from mytable where age in (18,19,20);
  67. # 通配符(用在开头匹配会非常慢)
  68. %:匹配>=0个任意字符
  69. _:匹配1个任意字符
  70. []:匹配集合内的字符(字符用或者连接)
  71. ^:否定
  72. LIKE
  73. # 计算字段
  74. AS:取别名
  75. CONCAT:连接两个字段
  76. TRIM:去除空格
  77. select concat(trim(col1),'(',trim(col2),')') as concat_col from mytable;
  78. # 函数
  79. AVG() -- 忽略NULL行)!!
  80. COUNT()
  81. MAX()
  82. MIN()
  83. SUM()
  84. select col,count(*) as num from mytable group by col;
  85. select col,count(*) as num from mytable group by col;
  86. select A,count(B) from mytable group by col order by xx;
  87. select col,count(*) as num from mytable where col>2 group by col having num>=2;
  88. select col,count(*) as num from mytable where col>2 group by col having num>=2;
  89. # 子查询
  90. select * from mytable where col1 in (select col2 from table2);
  91. select cust_name,(select count(*) from Orders where Orders.cust_id = Customers.cust_id) as orders_num from Customers ORDER BY cust_name;
  92. # 连接(可以替代子查询)
  93. select A.value,B.value from tablea as A inner join tableb as B on A.key=B.key;
  94. select A.value,B.value from A,B on A.id=B.id;
  95. -- 自连接
  96. select A.name from employee as A inner join employee as B on(!!) A.department=B.department and B.name="Jim";
  97. select e1.name from employee as e1 inner join employee as e2 on e1.department=d2.department and e2.name="Jim";
  98. -- 外连接
  99. select Customers.cust_id,Customers.cust_name,Orders.order_id from Customers left outer join Orders on Customers.cust_id = Orders.cust_id;
  100. # 组合查询(默认去重、只能包含一个order by)
  101. select * from mytable where col=1 union select * from mytable where col=2;
  102. # 视图(虚拟的表,本身不包含数据,无法进行索引操作)
  103. create view myview as
  104. select concat(col1,col2) as concat_col from mytable where col=val;
  105. # 存储过程(自定义分隔符,预先编译,类似函数的作用,变量赋值)
  106. delimiter //
  107. create procedure myprocedure(out ret int)
  108. begin
  109. declare y int;
  110. select sum(col1) from mytable into y;
  111. select y*y into ret;
  112. end //
  113. delimiter ;
  114. delimiter //
  115. create procedure myprocedure(out ret int)
  116. begin
  117. declare y int;
  118. select sum(col1) from mytable into y;
  119. select y*y into ret;
  120. end //
  121. delimiter ;
  122. call myprocedure(@ret);
  123. select @ret;
  124. # 游标
  125. -- 主要用于交互式应用,其中用户需要对数据集中的任意行进行浏览和修改。
  126. -- 步骤:声明游标;打开游标;取出数据;关闭游标
  127. delimiter //
  128. create procedure myprocedure(out ret int)
  129. begin
  130. declare done boolean default 0;
  131. #声明游标
  132. declare mycursor cursor for
  133. select col1 from mytable;
  134. # 定义continue handler,当 sqlstate '02000'这个条件出现时,执行set done=1
  135. declare continue handler for sqlstate '02000' set done = 1;
  136. #打开游标
  137. open mycursor;
  138. #取出数据
  139. repeat
  140. fetch mycursor into ret;
  141. select ret;
  142. until done end repeat;
  143. #关闭游标
  144. close mycursor;
  145. end //
  146. delimiter ;
  147. # 触发器
  148. -- 在某个表执行以下语句时自动执行:DELETE\INSERT\UPDATE
  149. -- 必须指定在语句执行之前还是之后自动执行
  150. -- 之前执行,用于数据验证和净化:before
  151. -- 之后执行,用于审计跟踪,将修改记录到另一张表中:after
  152. create trigger mytrigger after insert on mytable for each row select NEW.col into @result;
  153. select @result; -- 获取结果
  154. -- insert触发器:包含一个名为NEW的虚拟表
  155. -- delete触发器:包含一个名为OLD的虚拟表,只读
  156. -- update触发器:包含一个名为NEW和一个名为OLD的虚拟表,其中NEW是可以被修改的,OLD是只读的
  157. -- MYSQL不允许在触发器中调用存储过程
  158. # 事务
  159. -- 基本术语
  160. -- 事务(transaction):一组SQL语句
  161. -- 回退(rollback):撤销指定SQL语句
  162. -- 提交(commit):将未存储的SQL语句结果写入数据库表
  163. -- 保留点(savepoint):事务处理中设置的临时占位符(placeholder),可以对它发布回退。
  164. -- 不能回退selectcreatedrop语句
  165. -- mysql事务提交默认是隐式提交,每执行一条语句就把这条语句当成一个事务然后提交。
  166. -- 当出现start transacion语句时,会关闭隐式提交;
  167. -- commitrollback语句执行后,事务会自动关闭,重新恢复隐式提交。
  168. -- 如果没有设置保留点,rollback会回推到start transaction语句处
  169. -- 如果设置了保留点,并且在rollback中指定该保留点,则会回退到该保留点处。
  170. start transaction
  171. savepoint delete1
  172. rollback to delete1
  173. commit
  174. # 字符集
  175. -- 字符集:字母和符号的集合
  176. -- 给表指定字符集
  177. create table mytable(
  178. col varchar(10) character set latin collate latin1_general_ci
  179. ) default character set hebrew collate hebrew_general_ci;
  180. -- 排序、分组时校对
  181. select * from mytable order by col collate latin1_general_ci;
  182. # 权限管理
  183. -- mysql账户信息保存在mysql数据库中
  184. use mysql;
  185. select user from user;
  186. -- 创建账户
  187. create user myuser identified by 'mypassword';
  188. -- 修改账户名
  189. rename user myuser to newuser;
  190. -- 删除账户
  191. drop user myuser;
  192. -- 查看权限
  193. show grants for myuser;
  194. -- 授予权限
  195. grant select,insert on mydatabase.* to myuser;
  196. -- 账户:username@host
  197. -- 默认主机名:username@%
  198. -- 删除权限
  199. -- 整个服务器:grant allrevoke all
  200. -- 整个数据库:on database.*
  201. -- 特定表:on database.table
  202. -- 特定列
  203. -- 特定存储过程
  204. revoke select, insert on mydatabase.* from myuser;
  205. -- 更改密码
  206. set password for myuser=Password('new_password');