1、创建视图:视图作为一种特殊的表,可以有效的封装sql查询,相当于给表封装上接口
//创建一个getNameAge的视图表,此表的内容为从user表中获取name、age字段,其他字段是不可见的
create view user_name_age as select name, age from user [where condition.....];
//使用视图
select * from user_name_age [where conditon....];
//删除视图
drop view user_name_age;
说到视图不得不提到比较冷门的一点:很多人觉得mysql没有select * from (select * from tableName)这样的查询语法,即在一结果集中二次筛选, 但,Every derived table must have its own alias
//即给结果集表要指定一个别名,这样from才能识别
select * from (select name, age from user) as user_name_age;
其实视图就好比一个查询结果集的别名,只不过他是固化的,而二次筛选指定的是临时的
2、将某一次的查询结果集存储到数据库表中
create table user_name_age as select name, age from user [where condition.....];
create table user_name_age(select name, age from user [where condition.....]);
以上两种方法都可以,第一种方式更能形象的说明view是一张特殊的表
但mysql没有
select * into tempTableName from tableName [where condition...]
方式的,其实一样,这里的tempTableName必须是不存在的表,和我们使用create语句一样
另外在写过程时我们可能会经常用到下面的语法为过程中声明的变量赋值
//
select name into variable from tableName
//
3、将查询结果插入某表中:注意没有 values
//
insert into user_name_age(name, age) select name, age from user;
//
4、rollup 和 group_concat() : rollup和group_concat()需要和group by连用,对组单位做统计
//
select age, count(*), group_concat(name order by name desc) from user group by age with rollup;
//
以age为分组,对同一age的用户进行分组,汇总他们的名字(group_concat)和人数,并在最后对总人数和总用户名进行汇总(rollup)
5、<=> 关系运算符
当我们查询某字段不为NULL的数据是不能用
select * from tableName where colName = NULL;
select * from tableName where colName <> NULL;
而应该使用
select * from tableName where colName IS NULL;
select * from tableName where colName IS NOT NULL;
select * from tableName where colName <=> NULL;
select * from tableName where NOT(colName <=> NULL);
6、ifnull()/isnull()/nullif()
//若参数1为null则返回默认值参数2
select ifnull(1, 2); //1
select ifnull(null, 2); //2
//判断参数是否为null
select isnull(1); //0
select isnull(null); //1
//两参数若相等则为null 若不等则为1
select nullif(1, 1); //null
select nullif(1, 2); //1