table of Contents
1.1 GROUP BY packet using
1.2 mysql in NOW (), CURDATE (), CURTIME () using
1.3 DATEDIFF () function
1.4 DATE_FORMAT () displays the time in a different format
1.5 MySQL regex
1.1 GROUP BY grouping use
GROUP BY introduction
1. GROUP BY 语句根据一个或多个列对结果集进行分组,在分组的列上我们可以使用 COUNT, SUM, AVG,等函数。
2. 涉及到的操作符:GROUP BY,HAVING,ORDER BY,INNER JOIN,OUT JOIN,AS,UNION。
2, Group basic use
- Create a table
CREATE TABLE user (
id int(11) NOT NULL,
name char(10) NOT NULL DEFAULT '',
date datetime NOT NULL,
singin tinyint(4) NOT NULL DEFAULT '0' COMMENT '登录次数',
PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- Inserting data into the table
INSERT INTO user VALUES
('1', '小明', '2016-04-22 15:25:33', '1'),
('2', '小王', '2016-04-20 15:25:47', '3'),
('3', '小丽', '2016-04-19 15:26:02', '2'),
('4', '小王', '2016-04-07 15:26:14', '4'),
('5', '小明', '2016-04-11 15:26:40', '4'),
('6', '小明', '2016-04-04 15:26:54', '2');
- Statistics of how many of the same name: Example 1
mysql> # SELECT name, COUNT(*) FROM user GROUP BY name;
+------+----------+
| name | COUNT(*) |
+------+----------+
| 小丽 | 1 |
| 小明 | 3 |
| 小王 | 2 |
+------+----------+
3 rows in set (0.01 sec)
- Group by name, and then count the number of each person who is registered: Example 2 with rollup
mysql># SELECT name, SUM(singin) as singin_count FROM user GROUP BY name WITH ROLLUP;
+------+--------------+
| name | singin_count |
+------+--------------+
| 小丽 | 2 |
| 小明 | 7 |
| 小王 | 7 |
| NULL | 16 |
+------+--------------+
4 rows in set (0.00 sec)
# WITH ROLLUP 可以实现在分组统计数据基础上再进行相同的统计(SUM,AVG,COUNT…)。
# 按姓名进行分组,再统计每个人登录的次数,其中记录 NULL 表示所有人的登录次数。
- Group by name, and then count the number of each person who is registered: Example 3 coalesce to set a name to replace NULL
mysql># SELECT coalesce(name, '总数'), SUM(singin) as singin_count FROM user GROUP BY name WITH ROLLUP;
+------------------------+--------------+
| coalesce(name, '总数') | singin_count |
+------------------------+--------------+
| 小丽 | 2 |
| 小明 | 7 |
| 小王 | 7 |
| 总数 | 16 |
+------------------------+--------------+
4 rows in set (0.00 sec)
#1、我们可以使用 coalesce 来设置一个可以取代 NUll 的名称,coalesce 语法:
#2、select coalesce(a,b,c);
#3、参数说明:如果a==null,则选择b;如果b==null,则选择c;如果a!=null,则选择a;如果a b c 都为null ,则返回为null(没意义)。
- Packet filtering HAVING: Find the number of users logged in Example 4 is greater than 2 for all the
mysql> SELECT name, SUM(singin) as singin_count FROM user GROUP BY name HAVING COUNT(*) >= 2;
+------+--------------+
| name | singin_count |
+------+--------------+
| 小明 | 7 |
| 小王 | 7 |
+------+--------------+
2 rows in set (0.00 sec)
- Students grouped by grade point average required subjects: Example 5
#1、创建表
create table student(
id int auto_increment,
name char(32) not null,
score int(10) not null,
course char(32) not null,
primary key (id));
#2、插入数据
insert into student(name,score,course) values('zhangsan',88,'english');
insert into student(name,score,course) values('zhangsan',98,'math');
insert into student(name,score,course) values('lisi',88,'math');
#3、查询
mysql> select *,avg(score) from student group by name;
+----+----------+-------+---------+------------+
| id | name | score | course | avg(score) |
+----+----------+-------+---------+------------+
| 4 | lisi | 88 | math | 88.0000 |
| 1 | zhangsan | 88 | english | 93.0000 |
+----+----------+-------+---------+------------+
2 rows in set (0.00 sec)
- 10 days before the user data of the same name registered users is greater than or equal to 2: Example 6
mysql># select *,count(name) from user where datediff(NOW(),date)>10 group by name having count(name)>=2;
+----+------+---------------------+--------+-------------+
| id | name | date | singin | count(name) |
+----+------+---------------------+--------+-------------+
| 1 | 小明 | 2016-04-22 15:25:33 | 1 | 3 |
| 2 | 小王 | 2016-04-20 15:25:47 | 3 | 2 |
+----+------+---------------------+--------+-------------+
2 rows in set (0.00 sec)
# 原题:请查找商品表中最近30天至少有20天都有销售记录的商品
1.2 mysql the NOW (), CURDATE (), CURTIME () using
- Example 1: NOW (), CURDATE (), CURDATE () action
mysql> SELECT NOW(),CURDATE(),CURTIME();
+---------------------+------------+-----------+
| NOW() | CURDATE() | CURTIME() |
+---------------------+------------+-----------+
| 2018-03-18 16:28:16 | 2018-03-18 | 16:28:16 |
+---------------------+------------+-----------+
1 row in set (0.00 sec)
- Example 2: Define the time field is automatically added to the table
#1、创建表
CREATE TABLE goods(
id int auto_increment,
name varchar(50) NOT NULL,
date datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
);
#2、插入一条数据
mysql># INSERT INTO goods(name) VALUES ('tea');
#3、验证时间字段会自动插入
mysql># select * from goods;
+----+------+---------------------+
| id | name | date |
+----+------+---------------------+
| 1 | tea | 2018-03-18 16:37:19 |
+----+------+---------------------+
1 row in set (0.00 sec)
1.3 DATEDIFF () function
- Example 1: Returns the number of days between two dates
mysql># SELECT DATEDIFF('2008-11-30','2008-11-22') AS DiffDate;
+----------+
| DiffDate |
+----------+
| 8 |
+----------+
1 row in set (0.00 sec)
- Example 2: Query the last five days of new data
#1、创建表
CREATE TABLE goods(
id int auto_increment,
name varchar(50) NOT NULL,
date datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
);
#2、插数据
INSERT INTO goods(name) VALUES ('tea1');
INSERT INTO goods(name) VALUES ('tea2');
INSERT INTO goods(name,date) VALUES ('tea3','2018-03-02 16:37:19');
INSERT INTO goods(name,date) VALUES ('tea4','2015-05-02 16:37:19');
#3、查询五天前的数据
mysql> select * from goods where datediff(NOW(),date)>5;
+----+------+---------------------+
| id | name | date |
+----+------+---------------------+
| 3 | tea3 | 2018-03-02 16:37:19 |
| 4 | tea4 | 2015-05-02 16:37:19 |
+----+------+---------------------+
2 rows in set (0.00 sec)
#4、查询最近五天的新数据
mysql> select * from goods where datediff(NOW(),date)<5;
+----+------+---------------------+
| id | name | date |
+----+------+---------------------+
| 1 | tea1 | 2018-03-18 16:56:42 |
| 2 | tea2 | 2018-03-18 16:56:43 |
+----+------+---------------------+
2 rows in set (0.00 sec)
1.4 DATE_FORMAT () displays the time in a different format
- Basic use DATE_FORMAT
select
DATE_FORMAT(NOW(),'%Y-%m-%d'),
DATE_FORMAT(NOW(),'%Y-%m-%d %H:%m:%s');
+-------------------------------+----------------------------------------+
| DATE_FORMAT(NOW(),'%Y-%m-%d') | DATE_FORMAT(NOW(),'%Y-%m-%d %H:%m:%s') |
+-------------------------------+----------------------------------------+
| 2018-03-18 | 2018-03-18 17:03:02 |
+-------------------------------+----------------------------------------+
1 row in set (0.00 sec)
1.5 MySQL Regular Expressions
1, MySQL commonly used in regular
mode | description |
---|---|
^ | Matches the beginning of the string. If the object is set RegExp Multiline property, also matches ^ '\ n' position after or '\ r'. |
$ | Matches the input end of the string. If the object is set RegExp Multiline property, $ also matches the position before the '\ n' or '\ r'. |
. | Matches any single character except "\ n" is. To match include '\ n', including any character, like the use of '[. \ N]' mode. |
[...] | Set of characters. Matches any character included. For example, '[abc]' matches "plain" in the 'a'. |
[^...] | Negative character sets. Matches any character not included. For example, '[^ abc]' matches "plain" the 'p'. |
p1-p2-p3 | Matching p1, p2, or p3. For example, 'z |
* | Matches the preceding subexpression zero or more times. For example, zo * matches "z" and "zoo". * Is equivalent to {0}. |
+ | Matches the preceding subexpression one or more times. For example, 'zo +' will match "zo" and "zoo", but can not match the "z". + Is equivalent to {1}. |
{n} | n is a nonnegative integer. Matching the determined n times. For example, 'o {2}' does not match the "Bob" in the 'o', but can match the "food" in the two o. |
{n,m} | m and n are non-negative integers, where n <= m. Match at least n times and match up to m times. |
2, MySQL regular Application Example
1、查找name字段中以'st'为开头的所有数据:
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';
2、查找name字段中以'ok'为结尾的所有数据:
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';
3、查找name字段中包含'mar'字符串的所有数据:
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';
4、查找name字段中以元音字符开头或以'ok'字符串结尾的所有数据:
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$';