About Mysql TIPS (continuous update)

  1. Aggregate functions cannot be directly followed by where.

  2. Generally speaking, if there is an aggregate function in select, you can only select the field by group (after group by) at the same time.

  3. The not in keyword will not automatically ignore the null value and needs to be removed manually; the in keyword will be automatically removed.

  4. Aggregate functions can be added to having (after group by is executed first, aggregate functions can be used)

  5. Subqueries can be added after select, from, where, and having.
    Among them, select is not commonly used. From generally uses the result of a subquery as a temporary table to link with the outer query. Where is similar to having, in which a subquery is first used to find a value and then help filter.

  6. Do not use any function to complete TOP N (using Cartesian product), group by has the effect of deduplication. (Only applicable when there is no same score)

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;
  1. When any value is compared with NULL using comparison operators (>,<,>=,<=,<>,=) or (in, not in, any/some, all), the return value is 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的查询结果都为空

Guess you like

Origin blog.csdn.net/qq_42962353/article/details/108685774