目录
[一,union all](#一,union all)
[四,字符串函数:LENGTH() 函数 / REPLACE()函数](#四,字符串函数:LENGTH() 函数 / REPLACE()函数)
一,union all
对查询结果进行连接 与 union 不同 union 不会去重
sql
SELECT
AVG(salary)
FROM `salaries8`
WHERE to_date = '9999-01-01' AND salary NOT IN (
SELECT MAX(salary) FROM `salaries8` AND to_date = '9999-01-01'
UNION ALL
SELECT MIN(salary) FROM `salaries8` AND to_date = '9999-01-01'
)
二,GROUP_CONCAT函数
可以将分组后的相同字段连接
sql
select
dept_no,
group_concat(emp_no) employees
from dept_emp
group by dept_no;
三,字符串函数:RIGHT()函数
从右向左获取字段的值 可以指定获取的个数
sql
SELECT
first_name
FROM `employees`
ORDER BY RIGHT(first_name,2)
四,字符串函数:LENGTH() 函数 / REPLACE()函数
LENGTH()函数用来获取字符串的长度 / replace(字段,"被替换值","替换的值")函数可以替换值
sql
SELECT id, (LENGTH(string) - LENGTH(REPLACE(string,",",''))) AS cnt FROM `strings`
sql
update titles_test
set titles_test.emp_no = replace(titles_test.emp_no, 10001, 10005)
where titles_test.id = '5';
五,条件更新表内的值
UPDATE "table_name" SET `字段` = "value" WHERE
sql
-- 更新数据库
UPDATE `salaries6` SET salary = 1.1 * salary
WHERE salaries6.emp_no IN (
SELECT emp_no FROM `emp_bonus`
) AND salaries6.to_date = '9999-01-01'
update titles_test set to_date = NULL, from_date = "2001-01-01"
where id in
(
select * from (
select id
from titles_test
where to_date = "9999-01-01"
) as t
)
六,创建外键
sql
ALTER TABLE audit ADD FOREIGN KEY (emp_no) REFERENCES employees_test(ID);
七,修改表名
sql
ALTER TABLE `titles_test` RENAME AS `titles_2017`
八,删除记录
sql
delete from titles_test
where id not in(
select min_id from (select min(id) as min_id from titles_test group by emp_no)t1);
九,构建触发器
sql
create trigger audit_log
after insert on employees_test
for each row
begin
insert into audit values(new.id,new.name);
end
十,增加属性字段
sql
ALTER TABLE actor ADD DELETE_date DATETIME NOT NULL DEFAULT '0000 00:00:00'