DataBase Base_函数&约束

DataBase Base_函数&约束

函数

AggregateFunction

Overview

An SQL aggregate function calculates on a set of values and returns a single value
Because an aggregate function operates on a set of values, it is often used with the GROUP BY clause of the SELECT statement. The GROUP BY clause divides the result set into groups of values and the aggregate function returns a single value for each group.
SQL Tutorial

The following are the commonly used SQL aggregate functions:

  • AVG() – returns the average of a set
  • COUNT() – returns the number of items in a set
  • COUNT(*) – returns the number of items in a set (including NULL values)
  • MAX() – returns the maximum value in a set
  • MIN() – returns the minimum value in a set
  • SUM() – returns the sum of all or distinct values in a set

Except for the COUNT() function, SQL aggregate functions ignore null.

You can use aggregate functions as expressions only in the following:

  • The select list of a SELECT statement, either a subquery or an outer query.
  • A HAVING clause

StringFunction

Functions that allow you to manipulate string data more effectively.

  • CONCAT(s1,s2,...,sn) – return the result of concatenation two strings together.
  • LOWER(str),UPPER(str) – converts a string to lower case or upper case.
  • LPAD(str,n,padstr),RPAD(str,n,padstr) – left/right pads a string with another string to a certain length.
  • TRIM(str),LTRIM(str),RTRIM(str) – removes all spaces from a string or from the left or right side of a string.
  • REPLACE(str,source,replace) – replaces all occurrences of a substring within a string with another substring.
  • SUBSTRING(str,pos,len) – returns a substring from a string starting at a specified position with a specified length.
    Reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
SELECT CONCAT('SQL',' is',' fun!');
+-------------------------+
| CONCAT("HELLO","WORLD") |
+-------------------------+
| HELLOWORLD |
+-------------------------+
SELECT LOWER("Hello,World");
+----------------------+
| LOWER("Hello,World") |
+----------------------+
| hello,world |
+----------------------+
SELECT RPAD("1",5,"Z");
+-----------------+
| RPAD("1",5,"Z") |
+-----------------+
| 1ZZZZ |
+-----------------+
SELECT RTRIM(" HELLO ");
+---------------------+
| RTRIM(" HELLO ") |
+---------------------+
| HELLO |
+---------------------+
SELECT REPLACE("Hello,World","World","SQL");
+--------------------------------------+
| REPLACE("Hello,World","World","SQL") |
+--------------------------------------+
| Hello,SQL |
+--------------------------------------+
SELECT SUBSTRING("Hello,World",1,5);
+------------------------------+
| SUBSTRING("Hello,World",1,5) |
+------------------------------+
| Hello |
+------------------------------+

Math Functions

SQL has many mathematical functions that allow you to perform business and engineering calculations.

  • ABS(x) – returns the absolute value of x.
  • CEIL(x) – returns the smallest integer that is greater than or equal to x.
  • FLOOR(x) – returns the largest integer that is less than or equal to x.
  • RAND() – returns a random floating-point value.
  • MOD(x,y) – returns the remainder(modulo) of x divided by y, MOD(10,7) returns 3. e.g.
  • ROUND(x,d) – returns a number rounded to d decimal places. ROUND(2.6666,3) returns 2.667 e.g.

Exercise

1
2
3
4
5
6
7
-- randomly generate 6 digits
SELECT SUBSTRING(ROUND(RAND(),6),3,6);
+--------------------------------+
| SUBSTRING(ROUND(RAND(),6),3,6) |
+--------------------------------+
| 578207 |
+--------------------------------+

Date Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
SELECT CURDATE(); -- YYYY-MM-DD
SELECT CURTIME(); -- HH:MM:SS
SELECT NOW(); -- YYYY-MM-DD HH:MM:SS

YEAR(date); MONTH(date); DAY(date);
SELECT YEAR("2023-1-2");
+------------------+
| YEAR("2023-1-2") |
+------------------+
| 2023 |
+------------------+

DATEADD(date,INTERVAL expr type);
DATEDIFF(date1,date2); -- date1 - date2

SELECT DATE_ADD(now(),INTERVAL 70 DAY);
+---------------------------------+
| DATE_ADD(now(),INTERVAL 70 DAY) |
+---------------------------------+
| 2024-04-06 20:09:20 |
+---------------------------------+
SELECT DATEDIFF(now(),"2023-1-20");
+-----------------------------+
| DATEDIFF(now(),"2023-1-20") |
+-----------------------------+
| 372 |
+-----------------------------+

Exercises

1
2
-- 查询每个员工的入职天数,并按照入职天数降序排列
SELECT Name,DATEDIFF(now(),entrydate) AS days FROM emp ORDER BY days DESC;

Control Flow Functions

1
2
3
4
5
6
7
8
--  if value is true, return if_true_expr, else return if_false_expr
IF(value,if_true_expr,if_false_expr)
-- if expr1 IS NULL, return expr2, else return expr1
IFNULL(expr1,expr2)
-- condition1为真,返回result1,condition2为真,返回result2,否则返回result
CASE WHEN <condition1> THEN <result1> WHEN <condition2> THEN <result2> ELSE <result> END
-- expr = value1, return result1, expr = value2, return result2, else return result
CASE <expr> WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE result END

Exercises

1
2
3
4
5
6
7
8
9
10
11
12
-- 查询emp表的员工的name,addr,如果addr为Beijing/Shanghai,则显示为一线城市,否则显示为二线城市
SELECT
name,
(CASE addr WHEN 'Beijing' THEN '一线城市' WHEN "Shanghai" THEN "一线城市" ELSE '二线城市' END) AS addrTag
FROM emp;

-- 查询学生成绩表,如果成绩大于等于60,显示及格,否则显示不及格
SELECT
name.
(CASE WHEN score >= 60 THEN '及格' ELSE '不及格' END AS) math,
(CASE WHEN english >= 60 THEN '及格' ELSE '不及格' END AS) english,
FROM score;

约束

Overview

概念: 约束是作用于表中字段上的规则,用于限制存储在表中的数据(类型、格式和范围等等)
目的: 保证数据的正确性、有效性和完整性
分类:

约束 描述 关键字
非空约束 限制该字段的数据不能为 null NOT NULL
唯一约束 保证该字段的所有数据都是唯一、不重复的 UNIQUE
主键约束 主键是一行数据的唯一标识,要求非空且唯一 PRIMARY KEY
默认约束 保存数据时,如果未指定该字段的值,则采用默认值 DEFAULT
检查约束(8.0.1 版本后) 保证字段值满足某一个条件 CHECK
外键约束 用来让两张图的数据之间建立连接,保证数据的一致性和完整性 FOREIGN KEY

Example

[DataBase01#DML] Review DML Syntax

1
2
3
4
5
6
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10) NOT NULL UNIQUE,
age TINYINT UNSIGNED CHECK(age>0 AND age<120),
gender ENUM('男','女','保密') DEFAULT '保密'
);

外键约束

概念 : 外键是表中的一个字段,它指向另一个表的主键,用来建立两张表之间的联系,保证数据的一致性和完整性

语法 : FOREIGN KEY (<foreignKey>) REFERENCES <tableName>(<primaryKey>)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-- 创建了两张表,Company表(主表,父表)中的Id字段是主键,Department表(子表,从表)中的depa_id字段是外键,指向Company表中的Id字
CREATE TABLE Company (
Id int NOT NULL,
name varchar(20) NOT NULL,
PRIMARY KEY (Id)
);

CREATE TABLE Department (
id int NOT NULL,
name varchar(20) NOT NULL,
salary decimal(10,2),
depa_id int,
PRIMARY KEY (id),
FOREIGN KEY (depa_id) REFERENCES Company(Id)
);
-- 添加外键约束
ALTER TABLE Department ADD CONSTRAINT fk_depa_id FOREIGN KEY (depa_id) REFERENCES Company(Id);
-- 删除外键约束
ALTER TABLE Department DROP FOREIGN KEY fk_depa_id;

删除/更新行为

行为 说明
NO ACTION 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与 RESTRICT 一致)
RESTRICT 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与 NO ACTION 一致)
CASCADE 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则也删除/更新外键在子表中的记录
SET NULL 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为 null(要求该外键允许为 null)
SET DEFAULT 父表有变更时,子表将外键设为一个默认值(Innodb 不支持)

设置删除/更新行为的语法:ON DELETE/UPDATE <action>
例如 ALTER TABLE Department ADD CONSTRAINT fk_depa_id FOREIGN KEY (depa_id) REFERENCES Company(Id) ON DELETE CASCADE ON UPDATE CASCADE;

Author

Efterklang

Posted on

2024-01-27

Updated on

2024-09-18

Licensed under

Comments