MySQL之select查询、function函数

时间:2023-03-10 07:13:04
MySQL之select查询、function函数

一、select查询

//查询某张表所有数据
select * from temp; //查询指定列和条件的数据
//查询name和age这两列,age等于22的数据
select name,age from temp where age = 22; //as对列重命名
//as可以省略不写,如果重命名的列名出现特殊字符,如单引号,那就需要用双引号引在外面
select name as '名称' from temp; //给table去别名
select t.name Name from temp as t; //where条件查询
>、>=、<、<=、=、<>都可以出现在where语句中
select from t where a > 2 or a>=3 or a<5 or a<=6 or a=7 or a<>0; //and 并且
//查询名称等于Jack并且年龄大于20的
select * from temp where age > 20 and name = 'jack'; //or或者
--满足一个条件即可
select * from temp where name = 'jack' or name = 'jackson'; //between v and v2
--大于等于v且小于等于v2
select * from temp where age between 20 and 25; //in 查询
--可以多个条件,类似于or
--查询id 在括号中出现的数据
select *from temp where id in (1, 2, 3); //like模糊查询
--查询name以j开头的
select * from temp where name like 'j%';
--查询name包含k的
select * from temp where name like '%k%';
--escape转义,指定\为转义字符,上面的就可以查询name中包含“_”的数据
select * from temp where name like '\_%' escape '\'; //is null、is not null
--查询为null的数据
select * from temp where name is null;
--查询不为null 的数据
select * from temp where name is not null; //order by
--排序,升序(desc)、降序(asc)
--默认升序
select * from temp order by id;
select * from temp order by id asc;
--多列组合
select * from temp order by id, age; //not
select * from temp where not (age > 20);
select * from temp where id not in(1, 2); //distinct去掉重复数据
select distinct id from temp;
//多列将是组合的重复数据
select distinct id, age from temp; //查询常量
select 5+2;
select concat('a', 'bbb'); //concat函数,字符串连接
//concat和null进行连接,会导致连接后的数据成为null
select concat(name, '-eco') from temp; //对查询的数据进行运算操作
select age +2, age / 2, age - 2, age * 2 from temp where age - 2 > 22;

 二、函数

函数类似于存储过程,只是调用方式不同

//创建函数
create function addAge(age int) returns int
return age + 5;
//使用函数:
select addAge(age) from temp;
//删除函数
drop function if exists addAge;
drop function addAge;
//显示创建语法
show create function addAge;

三、触发器

触发器分为insert、update、delete三种触发器事件类型,还有after、before触发时间

//创建触发器
create trigger trg_temp_ins
before insert
on temp for each row
begin
insert into temp_log values(NEW.id, NEW.name);
end
//删除触发器
drop trigger trg_temp_ins