You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL左连接查询如何将左表重复的关联字段值设置为空

实现同员工仅第一条请假记录展示ID的SQL方案

现有数据表说明

  • table1(员工表):存储员工基础信息,包含EmployeeId、Employee Name两个字段,示例数据如下:
EmployeeIdEmployee Name
1Employee1
2Employee2
  • table2(请假记录表):存储员工请假记录,包含EmployeeId、Leave Date两个字段,示例数据如下:
EmployeeIdLeave Date
101/08/2021
201/08/2021
102/08/2021
303/08/2021
104/08/2021
205/08/2021

原有问题修正

你提供的初始查询存在两处笔误:表名table 2存在非法空格,关联条件中table1.EmplaoyeeId拼写错误,可先修正后再参考以下方案实现需求。

具体实现方案

主流数据库通用方案(支持窗口函数场景)

通过ROW_NUMBER()窗口函数给同员工的请假记录按日期排序,仅第一条记录返回员工ID,其余行返回空值即可:

SELECT 
  CASE WHEN row_num = 1 THEN t1.EmployeeId ELSE NULL END AS EmployeeId,
  t2.`Leave Date` AS LeaveDate
FROM table1 t1
INNER JOIN (
  SELECT 
    EmployeeId,
    `Leave Date`,
    ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY `Leave Date` ASC) AS row_num
  FROM table2
) t2 ON t1.EmployeeId = t2.EmployeeId
ORDER BY t1.EmployeeId, t2.`Leave Date` ASC;

执行逻辑说明

  1. 子查询中按EmployeeId分组,每组内按请假日期升序排序,为每条记录生成唯一行号
  2. 外层查询通过CASE判断,仅行号为1的记录(即该员工第一条请假记录)展示员工ID,其余行对应位置为空
  3. 最终结果按员工ID、请假日期升序排序,符合常规展示需求

返回结果示例

EmployeeIdLeaveDate
101/08/2021
NULL02/08/2021
NULL04/08/2021
201/08/2021
NULL05/08/2021

低版本数据库兼容方案(不支持窗口函数场景)

如果使用不支持窗口函数的低版本数据库(如MySQL 5.7及更早版本),可通过关联聚合子查询实现:

SELECT 
  CASE WHEN t2.`Leave Date` = t_min.first_leave_date THEN t1.EmployeeId ELSE NULL END AS EmployeeId,
  t2.`Leave Date` AS LeaveDate
FROM table1 t1
INNER JOIN table2 t2 ON t1.EmployeeId = t2.EmployeeId
INNER JOIN (
  SELECT EmployeeId, MIN(`Leave Date`) AS first_leave_date
  FROM table2
  GROUP BY EmployeeId
) t_min ON t2.EmployeeId = t_min.EmployeeId
ORDER BY t1.EmployeeId, t2.`Leave Date` ASC;

内容的提问来源于stack exchange,提问作者tarunhv1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:27:02