平时业务中多组条件两列同时满足的sql,可能大家会这样写
表结构:
id a b
1 1 2
2 3 4
3 5 6
4 7 8
5 1 4
6 9 10
sql:
select a,b
from test
where (a = 1 and b = 2)
or (a = 3 and b = 4)
or (a = 5 and b = 6)
or (a = 7 and b = 8);
当条件一多就会显的sql
特别乱,其实mysql
的in
就可以解决这种情况
select a,b
from test
where (a,b) in ((1,2),(3,4),(5,6),(7,8));
执行sql
,得到以下结果
a b
1 2
3 4
5 6
7 8
Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。
±—±------±-------±-------------+
| Id | Name | Salary | DepartmentId |
±—±------±-------±-------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
±—±------±-------±-------------+
Department 表包含公司所有部门的信息。
±—±---------+
| Id | Name |
±—±---------+
| 1 | IT |
| 2 | Sales |
±—±---------+
编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)。
±-----------±---------±-------+
| Department | Employee | Salary |
±-----------±---------±-------+
| IT | Max | 90000 |
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
±-----------±---------±-------+
Result:
思路就是先找出每个部门里money
最多的,此时就可以获取到部门类别id
和max money
,然后利用mysql
多列in
的操作,就可以取出部门中money
最多的人的信息
并且这里要考虑到Department
表可能为空的情况,left join
时右表为空的时候,单单只有左表的值,不符合要求
select de.Name as Department,em.Name as Employee,em.Salary
from Employee em
left join Department de
on em.DepartmentId = de.id
where
de.id is not null
and
(em.DepartmentId ,em.Salary) in (
select DepartmentId ,max(Salary) from Employee group by DepartmentId
)
demo案例来自力扣
https://leetcode-cn.com/problems/department-highest-salary/
mysql多列in参考自
https://blog.csdn.net/leonin12/article/details/106546623