MySQL运算符

运算符是用来连接表达式中各个操作数的符号,其作用是用来指明对操作数所进行的运算。MySQL数据库支持使用4种运算符,分别是算术运算符、比较运算符、逻辑运算符和位运算符。

运算符简介
算术运算符包括加减乘除和余这几种,主要用于数值计算
比较运算符包括>、<、=、!=、is null运算符,主要用于数值比较、字符串匹配
逻辑运算符包括与或非和异或等逻辑运算,运算结果只返回真假。
位运算符包括按位与、按位或、按位取反、按位异或、按位左移和按位右移。这些运算必须先变数值为二进制,然后在二进制数上操作。

算术运算符

\\创建一个字段为a值为24的t1表
mysql> create table t1(a int not null primary key);
mysql> insert into t1 values(24);
\\执行加减乘运算
mysql> select a,a+5+2,a-5-2,a*5*2 from t1;
+----+-------+-------+-------+
| a  | a+5+2 | a-5-2 | a*5*2 |
+----+-------+-------+-------+
| 24 |    31 |    17 |   240 |
+----+-------+-------+-------+
\\除运算和取余运算
mysql> select a,a/3,a div 3,a%3,mod(a,3) from t1;
+----+--------+---------+------+----------+
| a  | a/3    | a div 3 | a%3  | mod(a,3) |
+----+--------+---------+------+----------+
| 24 | 8.0000 |       8 |    0 |        0 |
+----+--------+---------+------+----------+

比较运算符

当使用select语句进行查询时,MySQL允许用户对表达式的左边操作数和右边操作数进行比较,结果为真,则返回1,为假则返回0,不确定则返回null.

符号形式作用
=x1=x2判断x1是否和x2相等
<>或!=x1<>x2/x1!=x2判断x1是否和x2不等
<=>x1<=>x2判断x1是否等于x2
>x1>x2判断x1是否大于x2
>=x1>=x2判断x1是否大于等于x2
<x1<x2判断x1是否小于x2
<=x1<=x2判断x1是否大于等于x2
is nullx1 is null判断x1是否等于null
is not nullx1 is not null判断x1是否不等于null
between andx1 BET判断x1是否在前后值之间
inx1 in(a,b,c,d,e,f)判断x1是否在列表之内
likex1 like 表达式判断x1是否与表达式匹配
regexpx1 regexp 正则表达式判断x1是否与正则表达式匹配
mysql> select 1=0,1=1,null=null;
+-----+-----+-----------+
| 1=0 | 1=1 | null=null |
+-----+-----+-----------+
|   0 |   1 |      NULL |
+-----+-----+-----------+
1 row in set (0.00 sec)

逻辑运算符

逻辑运算符又被称为布尔运算符,返回的结果只有1和0.

符号名称符号名称
&&/and!/NOT
II/ORXOR异或
mysql> select not 0,not 1,not null;
+-------+-------+----------+
| not 0 | not 1 | not null |
+-------+-------+----------+
|     1 |     0 |     NULL |
+-------+-------+----------+
mysql> select (1 and 1),(0 and 1),(3 and 1),(1 and null);
+-----------+-----------+-----------+--------------+
| (1 and 1) | (0 and 1) | (3 and 1) | (1 and null) |
+-----------+-----------+-----------+--------------+
|         1 |         0 |         1 |         NULL |
+-----------+-----------+-----------+--------------+

位运算符

位运算符是在二进制数上进行计算的运算符。位运算会先将操作数变成二进制数,然后进行位运算,最后再将计算结果从二进制数变回十进制数。

符号名称符号名称
&按位与^按位异或
I按位或<<按位左移
~按位取反>>按位右移

tips:I替代了|,II替代||

mysql> select 2&3;
+-----+
| 2&3 |
+-----+
|   2 |
+-----+
1 row in set (0.00 sec)

MySQL的增删改

数据库通过插入、更新和删除等方式来改变表中的记录。插入数据是向表中插入新的记录,通过insert语句实现。更新数据是改变表中已经存在的数据,使用update语句来实现。删除数据是删除表中不再使用的数据,通过delete语句来实现。

插入数据

mysql> create table product(id int(10) primary key not  null, name varchar(20) not null, function varchar(50), company varchar(20) not null, address varchar(50));
\\为所有字段插入数据
mysql> insert into product values(1001,'ABC药物','治疗感冒','ABC制药厂','北京市昌平区十三陵');
\\列出所有字段
mysql> insert into product(id,name,function,company,address) values(1002,'BCD','治.头疼 ','BCD制药厂','北京市海淀区蓝靛厂');
\\变更顺序,不影响输入
mysql> insert into product(id,function,name,address,company) values(1003,'治疗癌症','AB康 复丸','北京市顺义区牛栏山','AB康复制药厂');
\\为表的指定字段插入数据
mysql> insert into product(id,name,company) values(1004,'EF咳嗽灵','EF健康公司');
mysql> insert into product(id,company,name) values(1005,'北京市制药厂','OK创可贴');
\\同时插入多条数据
mysql> insert into product values (1006,'头疼灵1号','治疗头疼','廊坊大厂制药厂','河北省廊 坊市大厂县'),  (1007,'头疼灵2号','延缓头疼','廊坊香河制药厂','河北省廊坊市香河县'),  (1008,'头疼灵3号','镇痛安眠','廊坊三河制药厂','河北省廊坊市三河县');
mysql> select * from product;
+------+---------------+--------------+-----------------------+-----------------------------+
| id   | name          | function     | company               | address                     |
+------+---------------+--------------+-----------------------+-----------------------------+
| 1001 | ABC药物       | 治疗感冒     | ABC制药厂             | 北京市昌平区十三陵          |
| 1002 | BCD           | 治疗头疼     | BCD制药厂             | 北京市海淀区蓝靛厂          |
| 1003 | AB康复丸      | 治疗癌症     | AB康复制药厂          | 北京市顺义区牛栏山          |
| 1004 | EF咳嗽灵      | NULL         | EF健康公司            | NULL                        |
| 1005 | OK创可贴      | NULL         | 北京市制药厂          | NULL                        |
| 1006 | 头疼灵1号     | 治疗头疼     | 廊坊大厂制药厂        | 河北省廊坊市大厂县          |
| 1007 | 头疼灵2号     | 延缓头疼     | 廊坊香河制药厂        | 河北省廊坊市香河县          |
| 1008 | 头疼灵3号     | 镇痛安眠     | 廊坊三河制药厂        | 河北省廊坊市三河县          |
+------+---------------+--------------+-----------------------+-----------------------------+

更新数据

修改单行数据
mysql> update product set function='治疗咽炎、咳嗽',address='北京市通州区马驹桥' where id=1004;
\\同时修改多个数据
mysql> update product set address=='河北省廊坊市香河县燕郊镇',company='廊坊制药厂' where id>1005 and id<=1008;
mysql> select * from product;
+------+---------------+-----------------------+--------------------+--------------------------------------+
| id   | name          | function              | company            | address                              |
+------+---------------+-----------------------+--------------------+--------------------------------------+
| 1001 | ABC药物       | 治疗感冒              | ABC制药厂          | 北京市昌平区十三陵                   |
| 1002 | BCD           | 治疗头疼              | BCD制药厂          | 北京市海淀区蓝靛厂                   |
| 1003 | AB康复丸      | 治疗癌症              | AB康复制药厂       | 北京市顺义区牛栏山                   |
| 1004 | EF咳嗽灵      | 治疗咽炎、咳嗽        | EF健康公司         | 北京市通州区马驹桥                   |
| 1005 | OK创可贴      | NULL                  | 北京市制药厂       | NULL                                 |
| 1006 | 头疼灵1号     | 治疗头疼              | 廊坊制药厂         | 河北省廊坊市香河县燕郊镇             |
| 1007 | 头疼灵2号     | 延缓头疼              | 廊坊制药厂         | 河北省廊坊市香河县燕郊镇             |
| 1008 | 头疼灵3号     | 镇痛安眠              | 廊坊制药厂         | 河北省廊坊市香河县燕郊镇             |
+------+---------------+-----------------------+--------------------+--------------------------------------+
8 rows in set (0.00 sec)

删除数据

mysql> delete from product where id=1005;
\\默认删除所有行数据
mysql> delete from product;

MySQL的查询数据

查询数据是指从数据库中获取所需的数据。查询数据是数据库中最常用,也是最重要的操作。用户可以根据自己的需求,使用不同的查询方式。


基本查询语句

select属性列表
from 表名和视图列表
where 条件表达式1
group by 属性名1 [having 条件表达式2]
order by 属性名2 [asc|desc]
\\显示员工表内的全部数据
mysql> select * from employee;
+-----+------+----------+------+-----+----------+
| num | d_id | name     | age  | sex | homeaddr |
+-----+------+----------+------+-----+----------+
|   1 | 1001 | zhangsan |   20 |   1 | beijing  |
|   2 | 1002 | lisi     |   24 |   0 | taiyuan  |
|   3 | 1004 | wangwu   |   29 |   1 | tianjin  |
|   4 | 1005 | zhaoliu  |   35 |   1 | tieling  |
|   5 | 1007 | maba     |   18 |   1 | luoyang  |
+-----+------+----------+------+-----+----------+
\\显示员工中小于25岁的人,并按num序号从大到小排列
mysql> select * from employee where age < 25 order by num desc;
+-----+------+----------+------+-----+----------+
| num | d_id | name     | age  | sex | homeaddr |
+-----+------+----------+------+-----+----------+
|   5 | 1007 | maba     |   18 |   1 | luoyang  |
|   2 | 1002 | lisi     |   24 |   0 | taiyuan  |
|   1 | 1001 | zhangsan |   20 |   1 | beijing  |
+-----+------+----------+------+-----+----------+
2 rows in set (0.00 sec)
\\查询指定字段,改变显示顺序,并按年龄排序
mysql> select age,name from employee order by age;
+------+----------+
| age  | name     |
+------+----------+
|   18 | maba     |
|   20 | zhangsan |
|   24 | lisi     |
|   29 | wangwu   |
|   35 | zhaoliu  |
+------+----------+
5 rows in set (0.00 sec)
\\查询指定记录,员工号大于等于1005的人员
mysql> select * from employee where d_id >= 1005;
+-----+------+---------+------+-----+----------+
| num | d_id | name    | age  | sex | homeaddr |
+-----+------+---------+------+-----+----------+
|   4 | 1005 | zhaoliu |   35 |   1 | tieling  |
|   5 | 1007 | maba    |   18 |   1 | luoyang  |
+-----+------+---------+------+-----+----------+
2 rows in set (0.00 sec)
\\带IN关键字的查询,将集合中的记录显示出来
mysql> select * from employee where num in(3,5);
+-----+------+--------+------+-----+----------+
| num | d_id | name   | age  | sex | homeaddr |
+-----+------+--------+------+-----+----------+
|   3 | 1004 | wangwu |   29 |   1 | tianjin  |
|   5 | 1007 | maba   |   18 |   1 | luoyang  |
+-----+------+--------+------+-----+----------+
\\带between and的范围查询
mysql> select age,name from employee where age between 15 and 25 order by age;
+------+----------+
| age  | name     |
+------+----------+
|   18 | maba     |
|   20 | zhangsan |
|   24 | lisi     |
+------+----------+
\\not是可选参数
mysql> select age,name from employee where age not between 15 and 25 order by age;
+------+---------+
| age  | name    |
+------+---------+
|   29 | wangwu  |
|   35 | zhaoliu |
+------+---------+
\\使用like字符匹配查询所有名字中带有a的人员
mysql> select num,name from employee where name like '%a%';
+-----+----------+
| num | name     |
+-----+----------+
|   1 | zhangsan |
|   3 | wangwu   |
|   4 | zhaoliu  |
|   5 | maba     |
+-----+----------+

\\可以使用is null来查询空值
\\使用and进行多条件查询,年龄小于25,名字带a的男性
mysql> select name,age,sex from employee where age between 15 and 25
    -> and sex = 1
    -> and name like '%a%';
+----------+------+-----+
| name     | age  | sex |
+----------+------+-----+
| zhangsan |   20 |   1 |
| maba     |   18 |   1 |
+----------+------+-----+
\\使用distinct来除重
mysql> select sex from employee;
+-----+
| sex |
+-----+
|   1 |
|   0 |
|   1 |
|   1 |
|   1 |
+-----+
mysql> select distinct sex from employee;
+-----+
| sex |
+-----+
|   1 |
|   0 |
+-----+
\\按组进行查询,并按组显示
mysql> select * from employee group by sex;
+-----+------+----------+------+-----+----------+
| num | d_id | name     | age  | sex | homeaddr |
+-----+------+----------+------+-----+----------+
|   2 | 1002 | lisi     |   24 |   0 | taiyuan  |
|   1 | 1001 | zhangsan |   20 |   1 | beijing  |
+-----+------+----------+------+-----+----------+
\\group by与group_contcat()函数一起使用,分组显示全部内容
mysql> select sex,group_concat(name) from employee group by sex;
+-----+------------------------------+
| sex | group_concat(name)           |
+-----+------------------------------+
|   0 | lisi                         |
|   1 | zhangsan,wangwu,zhaoliu,maba |
+-----+------------------------------+
\\group by与集合函数一起使用
mysql> select sex,count(sex) from employee group by sex;
+-----+------------+
| sex | count(sex) |
+-----+------------+
|   0 |          1 |
|   1 |          4 |
+-----+------------+
\\group by 与having一起使用
mysql> select sex,count(sex) from employee group by sex having count(sex)>3;
+-----+------------+
| sex | count(sex) |
+-----+------------+
|   1 |          4 |
+-----+------------+
\\where作用于表或者视图,是表和试图的查询条件。
\\having作用于分组后的记录,用于选择满足条件的组。
\\多个字段分组,第一个组相同,则按第二个组排序,同样1001的按年龄排
mysql> select d_id,group_concat(name),age from employee group by d_id,age;
+------+--------------------+------+
| d_id | group_concat(name) | age  |
+------+--------------------+------+
| 1001 | maba               |   18 |
| 1001 | zhangsan           |   20 |
| 1002 | lisi               |   24 |
| 1004 | wangwu             |   29 |
| 1005 | zhaoliu            |   35 |
+------+--------------------+------+
\\group by与with rollup进行汇总
mysql> select sex,count(sex) from employee group by sex with rollup;
+-----+------------+
| sex | count(sex) |
+-----+------------+
|   0 |          1 |
|   1 |          4 |
| NULL |          5 |
+-----+------------+
\\使用limit限制查询结果的数量
mysql> select * from employee limit 2;
+-----+------+----------+------+-----+----------+
| num | d_id | name     | age  | sex | homeaddr |
+-----+------+----------+------+-----+----------+
|   1 | 1001 | zhangsan |   20 |   1 | beijing  |
|   2 | 1002 | lisi     |   24 |   0 | taiyuan  |
+-----+------+----------+------+-----+----------+
2 rows in set (0.00 sec)
mysql> select * from employee limit 4;
+-----+------+----------+------+-----+----------+
| num | d_id | name     | age  | sex | homeaddr |
+-----+------+----------+------+-----+----------+
|   1 | 1001 | zhangsan |   20 |   1 | beijing  |
|   2 | 1002 | lisi     |   24 |   0 | taiyuan  |
|   3 | 1004 | wangwu   |   29 |   1 | tianjin  |
|   4 | 1005 | zhaoliu  |   35 |   1 | tieling  |
+-----+------+----------+------+-----+----------+
4 rows in set (0.00 sec)
\\指定初始位置
mysql> select * from employee limit 2,4;
+-----+------+---------+------+-----+----------+
| num | d_id | name    | age  | sex | homeaddr |
+-----+------+---------+------+-----+----------+
|   3 | 1004 | wangwu  |   29 |   1 | tianjin  |
|   4 | 1005 | zhaoliu |   35 |   1 | tieling  |
|   5 | 1001 | maba    |   18 |   1 | luoyang  |
+-----+------+---------+------+-----+----------+
3 rows in set (0.00 sec)

tips:

在MySQL5.7以后的group by中会直接报1055的错误。
原因是5.7后的版本默认开启only_full_group_by属性,需要在group by查询中使用any_value()函数。
解决的方法一个是改查询语句,一个是改配置文件。
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
在[mysqld]字段新增一行配置
sql_mode=STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
然后,
sudo service mysql restart


使用集合函数查询

\\count()函数,统计函数
mysql> select count(*) from employee;
\\sum()函数,求和函数
mysql> select d_id,sum(age) from employee;
\\avg()函数,求平均值函数
mysql> select avg(age) from employee group by sex;
\\max()函数,求最大值函数
mysql> select max(age) from employee;
\\min()函数,求最小值函数
mysql> select min(age) from employee;

连接查询

\\内连接查询
mysql> select * from employee;
+-----+------+--------+-----+-----+----------------------------------+
| num | d_id | name   | age | sex | homeaddr                         |
+-----+------+--------+-----+-----+----------------------------------+
|   1 | 1001 | 张三   |  26 | 男  | 北京市海淀区学院路16号           |
|   2 | 1001 | 李四   |  24 | 女  | 北京市昌平区北七家镇             |
|   3 | 1004 | Aric   |  18 | 男  | England                          |
+-----+------+--------+-----+-----+----------------------------------+
3 rows in set (0.00 sec)
mysql> select * from department;
+------+-----------+--------------+---------------------+
| d_id | d_name    | function     | address             |
+------+-----------+--------------+---------------------+
| 1001 | 研发部    | 产品研发     | 3号楼5层            |
| 1002 | 生产部    | 产品制造     | 5号楼1层            |
| 1003 | 销售部    | 产品销售     | 1号楼销售大厅       |
+------+-----------+--------------+---------------------+
mysql> select num,name,employee.d_id,age,sex,d_name,function from employee,department where employee.d_id=department.d_id;
+-----+--------+------+-----+-----+-----------+--------------+
| num | name   | d_id | age | sex | d_name    | function     |
+-----+--------+------+-----+-----+-----------+--------------+
|   1 | 张三   | 1001 |  26 | 男  | 研发部    | 产品研发     |
|   2 | 李四   | 1001 |  24 | 女  | 研发部    | 产品研发     |
|   4 | 王五   | 1003 |  25 | 女  | 销售部    | 产品销售     |
mysql> select num,name,employee.d_id,age,sex,d_name,function from employee,department where employee.d_id=department.d_id;
+-----+--------+------+-----+-----+-----------+--------------+
| num | name   | d_id | age | sex | d_name    | function     |
+-----+--------+------+-----+-----+-----------+--------------+
|   1 | 张三   | 1001 |  26 | 男  | 研发部    | 产品研发     |
|   2 | 李四   | 1001 |  24 | 女  | 研发部    | 产品研发     |
|   4 | 王五   | 1003 |  25 | 女  | 销售部    | 产品销售     |
+-----+--------+------+-----+-----+-----------+--------------+
\\左连接查询 left join 表名 on 条件
mysql> select num,name,employee.d_id,age,sex,d_name,function from employee left join department  on employee.d_id=department.d_id;
\\右连接查询 right join 表名 on 条件
mysql> select num,name,employee.d_id,age,sex,d_name,function from employee right join department  on employee.d_id=department.d_id;

子查询

\\带in关键字的子查询
mysql> select * from employee where d_id in(select d_id from department);
+-----+------+--------+-----+-----+----------------------------------+
| num | d_id | name   | age | sex | homeaddr                         |
+-----+------+--------+-----+-----+----------------------------------+
|   1 | 1001 | 张三   |  26 | 男  | 北京市海淀区学院路16号           |
|   2 | 1001 | 李四   |  24 | 女  | 北京市昌平区北七家镇             |
|   4 | 1003 | 王五   |  25 | 女  | 北京市朝阳区双桥                 |
+-----+------+--------+-----+-----+----------------------------------+
\\not查询反向
mysql> select * from employee where d_id not in(select d_id from department);
+-----+------+------+-----+-----+----------+
| num | d_id | name | age | sex | homeaddr |
+-----+------+------+-----+-----+----------+
|   3 | 1004 | Aric |  18 | 男  | England  |
+-----+------+------+-----+-----+----------+


MySQL的触发器

触发器(Trigger)是由事件来触发某个操作。当数据库系统执行这些事件时,就会激活触发器执行相应的操作。

创建触发器

创建只有一个执行语句的触发器

\\create trigger 触发器名 before|after 触发事件 on 表名
\\      for each row 执行语句
mysql> create trigger user_trig1 before insert on user for each row insert into  trigger_time values(now());

mysql> insert into user(id,name,num,phone,address,age,sex) values(2,'su bowen',2,1861225,'tongzhou',4,1);
Query OK, 1 row affected (0.00 sec)
mysql> select * from user;
+----+----------+------+---------+----------+-----+------+
| id | name        | num  | phone   | address  | age | sex  |
+----+----------+------+---------+----------+-----+------+
|  1 | su jingxuan |    1 | 1861109 | beijing  |  35 |    1 |
|  2 | su bowen    |    2 | 1861225 | tongzhou |   4 |    1 |
mysql> select * from trigger_time;
+---------------------+
| exec_time           |
+---------------------+
| 2017-08-13 16:22:14 |
+---------------------+

创建有多个执行语句的触发器

一般情况下,MySQL默认使用;作为结束执行语句。在创建触发器过程中需要用到;。为了解决这个问题可以用DELIMITER语句。如"delimiter&&",可以将结束符号变成&&。当触发器创建完成之后,可以用命令delimiter;来将结束符号还原。

mysql> delimiter&&
mysql> create trigger user_trig2 after delete on user for each row begin insert into trigger_time values('21:00:01'); insert into trigger_time values('22:00:02'); end&&
mysql>delimiter ;
mysql> create table trigger_time(exec_time time);
mysql> delete from user where id=2;
mysql> select * from trigger_time;
+-----------+
| exec_time |
+-----------+
| 21:00:01  |
| 22:00:02  |
+-----------+
mysql> select * from user;                                                            
+----+-------------+------+---------+---------+-----+------+
| id | name        | num  | phone   | address | age | sex  |
+----+-------------+------+---------+---------+-----+------+
|  1 | su jingxuan |    1 | 1861109 | beijing |  35 |    1 |
+----+-------------+------+---------+---------+-----+------+

查看触发器

mysql> show triggers\G
*************************** 1. row ***************************
             Trigger: user_trig1
               Event: INSERT
               Table: user
           Statement: insert into  trigger_time values(now())
              Timing: BEFORE
             Created: 2017-08-13 16:20:33.95
            sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
             Definer: sujx@%
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
*************************** 2. row ***************************
             Trigger: user_trig2
               Event: DELETE
               Table: user
           Statement: begin
insert into trigger_time values('21:00:01');
insert into trigger_time values('22:00:02');
end
              Timing: AFTER
             Created: 2017-08-13 16:30:24.44
            sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
             Definer: sujx@%
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
2 rows in set (0.00 sec)
\\可以在trigger表中查看触发器信息
mysql> select * from information_schema.triggers\G

触发器的使用

在MySQL中,触发器执行的顺序是before触发器、表操作、after触发器。

删除触发器

mysql> drop trigger user_trig1;