MySQL Basics - Functions and Constraints

This article introduces the commonly used functions in MySQL SQL statements and the constraints of table fields

Function classification

  • string functions
  • Numeric function
  • date function
  • process function

string functions

insert image description here
example:

-- 拼接
SELECT CONCAT('Hello', 'World');

-- 小写
SELECT LOWER('Hello');

-- 大写
SELECT UPPER('Hello');

-- 左填充
SELECT LPAD('01', 5, '-');

-- 右填充
SELECT RPAD('01', 5, '-');

-- 去除空格
SELECT TRIM(' Hello World ');

-- 切片(起始索引为1SELECT SUBSTRING('Hello World', 1, 5);

-- 由于业务需求变更,企业员工工号统一为5位数,不足5位数的全部在前面补0.
UPDATE emp SET workno = LPAD(workno,5,'0');

Numeric function

insert image description here
example:

#通过函数,生成一个六位数的随机验证码
SELECT LPAD(ROUND(RAND()*1000000,0),6,0);

date function

insert image description here
example:

#查询所有员工的入职天数
SELECT name,DATEDIFF(CURDATE(),entrydate) AS entryday  FROM EMP ORDER BY entryday DESC;

process function

insert image description here

select
    name,
    (case when age > 30 then '中年' else '青年' end)
from employee;
select
    name,
    (case workaddress when '北京市' then '一线城市' when '上海市' then '一线城市' else '二线城市' end) as '工作地址'
from employee;

constraint

Concept: Constraints are rules that act on fields in a table to limit the data stored in the table.
Purpose: To ensure the correctness, effectiveness and integrity of the data in the database.

insert image description here
Notice:

  • Constraints are applied to the fields in the table, and constraints can be added when creating/modifying tables

common constraints

insert image description here

create table user(
    id int primary key auto_increment,
    name varchar(10) not null unique,
    age int check(age > 0 and age < 120),
    status char(1) default '1',
    gender char(1)
);

foreign key constraints

Add foreign key:

CREATE TABLE 表名(
    字段名 字段类型,
    ...
    [CONSTRAINT] [外键名称] FOREIGN KEY(外键字段名) REFERENCES 主表(主表列名)
);
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表(主表列名);
-- 例子
alter table emp add constraint fk_emp_dept_id foreign key(dept_id) references dept(id);

Remove foreign keys:
ALTER TABLE 表名 DROP FOREIGN KEY 外键名;

example:

#为emp表的dept_id字段添加外键,关联dept表的id字段。
ALTER TABLE emp ADD CONSTRAINT fk_emp_dept_id FOREIGN KEY(dept_id) REFERENCES dept(id);

#删除名为fk_emp_dept_id的外键
ALTER TABLE emp DROP FOREIGN KEY fk_emp_dept_id;

delete/update behavior

insert image description here
Change delete/update behavior:
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段) REFERENCES 主表名(主表字段名) ON UPDATE 行为 ON DELETE 行为;

Guess you like

Origin blog.csdn.net/baidu_33256174/article/details/130670987