select employee_number, card_number FROM ( SELECT id, employee_number, card_number FROM ( SELECT case when LENGTH(pin) = 5 THEN CONCAT('000', pin) ELSE pin end as employee_number, cardno as card_number, '' AS id from gate_staff union ALL SELECT employee_number, card_number, id FROM gate_mdm_dm_cardinfo WHERE id in ( SELECT max(id) as maxId FROM gate_mdm_dm_cardinfo a INNER JOIN ( SELECT employee_number, MAX(last_update_time) max_date FROM gate_mdm_dm_cardinfo WHERE last_update_time <![CDATA[ >= ]]> #{startTime} AND last_update_time <![CDATA[ <= ]]> #{endTime} GROUP BY employee_number ) b ON a.employee_number = b.employee_number AND a.last_update_time = b.max_date GROUP BY a.employee_number) and status = 1 and public_flag = 'Y' ) as mid group by employee_number, card_number having count(*) = 1 ) AS ccc WHERE ccc.id != ''; 优化这段代码
时间: 2024-02-10 20:27:02 浏览: 164
row_number.rar_SQL中row_number用法_number
可以尝试对这段代码进行优化的几个方面:
1. 使用JOIN替代子查询:将gate_mdm_dm_cardinfo表中的子查询替换为JOIN操作,可以提高查询性能。将子查询中的条件移至ON子句中,以减少结果集大小。
```sql
SELECT employee_number, card_number
FROM (
SELECT id, employee_number, card_number
FROM (
SELECT CASE
WHEN LENGTH(pin) = 5 THEN CONCAT('000', pin)
ELSE pin
END AS employee_number,
cardno AS card_number,
'' AS id
FROM gate_staff
UNION ALL
SELECT employee_number, card_number, id
FROM gate_mdm_dm_cardinfo a
INNER JOIN (
SELECT employee_number, MAX(last_update_time) max_date
FROM gate_mdm_dm_cardinfo
WHERE last_update_time >= #{startTime} AND last_update_time <= #{endTime}
GROUP BY employee_number
) b ON a.employee_number = b.employee_number AND a.last_update_time = b.max_date
WHERE a.status = 1 AND a.public_flag = 'Y'
) AS mid
GROUP BY employee_number, card_number
HAVING COUNT(*) = 1
) AS ccc
WHERE ccc.id != '';
```
2. 添加索引:根据查询中涉及的字段,在gate_staff表和gate_mdm_dm_cardinfo表上添加适当的索引,以加快查询速度。
3. 优化查询计划:使用数据库的查询优化工具,如EXPLAIN语句,来分析查询计划并进行优化。根据分析结果,可以考虑调整查询的顺序、添加或删除索引等操作。
请注意,实际优化效果可能因数据库的特性和数据量而有所不同。建议在进行任何更改之前先备份数据库,并在测试环境中进行验证。
阅读全文