首页 > 解决方案 > with, ifnull, 关于 mysql 中 = 和 := 的问题

问题描述

我正在写一个只呈现第n个最高薪水的语句例如从下表中获取第二高薪水,结果是200。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

如果我写:

declare M int;
set M = N-1;
with s as (select distinct Salary 
          from Employee
          order by Salary desc
          limit M, 1)
select ifnull(s, null) as getNthHighestSalary

它报告不存在,但如果我写:

 declare M int;
 set M = N-1;

 select ifnull(
          (select distinct Salary 
          from Employee
          order by Salary desc
          limit M, 1), null) as getNthHighestSalary

它会起作用的。我理解“with as”创建临时表,但我不明白为什么 ifnull() 找不到 s。

另外,设置 M = N-1 和 M:= N-1 具有相同的结果,谁能向我解释一下“:=”或“=”哪个更好?

标签: mysql

解决方案


s 是表别名,传递给 ifnull 的列是 s.Salary。

SET 可以取=or :=,没有区别。


推荐阅读