-
where 后面不能直接跟聚合函数。
-
一般来说,select中有聚合函数的话,只能再同时选出分组依据的字段(group by 后面的)。
-
not in关键字不会自动忽略null值,需要手动剔除;in关键字会自动剔除。
-
having中可以加聚合函数(先执行group by后,就可以使用聚合函数了)
-
select、from、where、having 后面都可以加子查询。
其中select不常用,from一般将子查询的结果作为临时表和外层查询联动,where和having类似,都是先用子查询查出一个值之后帮助过滤。 -
不用任何函数完成TOP N(利用笛卡尔积),group by有去重的作用。(仅适用于没有相同的分数的情况)
SELECT
*
FROM
emp a
INNER JOIN
emp b
GROUP BY
a.empno
HAVING
sum(a.sal > b.sal) >=9(数据数-N)
ORDER BY
a.sal desc;
- 任何值和NULL使用比较运算符(>,<,>=,<=,<>,=)或者(in, not in, any/some, all)比较时,返回值都为NULL
select * from test;
+------+------+
| a | b |
+------+------+
| 1 | 1 |
| 1 | NULL |
| NULL | NULL |
+------+------+
mysql> select * from test1 where a in (null);
Empty set (0.00 sec)
mysql> select * from test1 where a in (null,1);
+------+------+
| a | b |
+------+------+
| 1 | 1 |
| 1 | NULL |
+------+------+
2 rows in set (0.00 sec)
-- 当in和null比较时,无法查询出为null的记录
mysql> select * from test1 where a not in (1);
Empty set (0.00 sec)
mysql> select * from test1 where a not in (null);
Empty set (0.00 sec)
mysql> select * from test1 where a not in (null,2);
Empty set (0.00 sec)
mysql> select * from test1 where a not in (2);
+------+------+
| a | b |
+------+------+
| 1 | 1 |
| 1 | NULL |
+------+------+
2 rows in set (0.00 sec)
-- 当not in后面有null值时,不论什么情况下,整个sql的查询结果都为空
- case when后面是可以跟and 和 or的,注意括号
select name, case when age < 10 and sex = 0 then '小男孩' else '其他' end as n from s;
select name, case when sex = 0 and sex = 1 then '男的女的' else '雌雄难辨' end as n from s;
- yyyymmddHHccss(至少年月日必须完整)格式的数字,‘yyyy-mm-dd HH:cc:ss’(至少年月日必须完整)格式的字符串会被自动识别为日期格式的数据
- 比如:先用date_format转换成日期格式的字符串,日期格式的字符串作为参数被传进datediff中时,会被识别成日期格式的数据
select datediff(date_format(20201024101010, '%Y-%m-%d %H:%c:%s'), date_format(20201025101010, '%Y-%m-%d %H:%c:%s'))
-- -1