我正在尝试列出我查询中的所有行,这些行将返回彼此相邻的所有重复项,以便我可以获取其ID,但我也想从结果中排除编号最小的id。我怎么能用我的查询来做这件事。
我的查询
SELECT
a.tail_number,
min(a.id),
b.aircraft_id
from aircraft a
left join jobs b on a.id = b.aircraft_id
where
a.active = 1 and b.aircraft_id is null
group by a.tail_number having count(*) > 1
当前输出
tail_number min(a.id) aircraft_id tail_count
125TH 4429 NULL 7
362FX 4223 NULL 7
439FL 4221 NULL 7
453FX 4220 NULL 7
455FX 4259 NULL 7
输出我试图实现
tail_number min(a.id) aircraft_id tail_count
125TH 4429 NULL 1
125TH 4430 NULL 1
125TH 4431 NULL 1
125TH 4432 NULL 1
362FX 4223 NULL 1
362FX 4224 NULL 1
362FX 4225 NULL 1
362FX 4226 NULL 1
答案 0 :(得分:1)
加入一个子查询,该子查询获得每个尾号的最低ID,然后将其从ON
条件中的结果中排除。
SELECT a.tail_number, a.id
FROM aircraft AS a
JOIN (SELECT tail_number, MIN(id) AS minid
FROM aircraft
WHERE active = 1
GROUP BY tail_number
HAVING COUNT(*) > 1) AS m ON a.tail_number = m.tail_number AND a.id != m.minid
LEFT JOIN jobs AS j ON a.id = j.aircraft_id
WHERE j.aircraft_id IS NULL
ORDER BY a.tail_number, a.id
我已将active = 1
和COUNT(*) > 1
的支票移动到子查询中,因为主查询中不再有任何分组。