删除多个联接上的重复行

时间:2013-10-05 10:19:45

标签: mysql sql

我有以下查询

select m.movementid, m.orderid, m.pickupdate, m.pickupnotes, 
b.bin_size, b.bin_type, 
l.address, l.suburb, l.postcode, l.state, 
if(rs.run_action = 'Pick', if (r.run_state = 'Active' or r.run_state='Ready', 1, 0), 0) as active_on_pick
from bb_movement m
inner join bb_bins b on b.bin_id = m.bin_id
inner join bb_location l on l.locationid = m.locationid
inner join bb_runsheet rs on rs.movement_id = m.movementid
inner join bb_run r on r.run_id = rs.run_id
where m.mvtstate = 'Active'
order by m.locationid, m.pickupdate

我想生成一个结果,其中active_on_pick列包含每个movementid的0或1。当给定的movementid添加到bb_run时,bb_runsheet表中存在记录 (bb_run可以有很多bb_runsheet记录,主要包含movementid)

我遇到的问题是当一个运行IS在运行时(即:有一个bb_run记录符合条件和bb_runsheet表中的一个条目)我在结果数据集中得到2行 - 例如:

mvt_id active_on_pick
21     0
21     1

我想要的只是21和1.我尝试了子查询和其他变体(例如movementid组),但似乎可以确定它。我正在使用mysql

2 个答案:

答案 0 :(得分:1)

我认为如果你将一些逻辑移入你的连接(改为LEFT JOIN),你可以得到答案,将更多逻辑移到另一个左连接中

select m.movementid, m.orderid, m.pickupdate, m.pickupnotes, 
b.bin_size, b.bin_type, 
l.address, l.suburb, l.postcode, l.state, 

IF(r.run_id IS NULL, 0, 1) as active_on_pick

from bb_movement m
inner join bb_bins b on b.bin_id = m.bin_id
inner join bb_location l on l.locationid = m.locationid

LEFT join bb_runsheet rs 
 ON rs.movement_id = m.movementid
    AND rs.run_action = 'Pick'

LEFT join bb_run r 
  ON r.run_id = rs.run_id
    AND (r.run_state = 'Active' or r.run_state='Ready')

where m.mvtstate = 'Active'
order by m.locationid, m.pickupdate

答案 1 :(得分:0)

你可以使用row_Number()

SELECT * FROM (    
select row_number() over (order by active_on_pick desc) rn,
m.movementid, m.orderid, m.pickupdate, m.pickupnotes, 
b.bin_size, b.bin_type, 
l.address, l.suburb, l.postcode, l.state, 
if(rs.run_action = 'Pick', if (r.run_state = 'Active' or r.run_state='Ready', 1, 0), 0) 
as active_on_pick
from bb_movement m
inner join bb_bins b on b.bin_id = m.bin_id
inner join bb_location l on l.locationid = m.locationid
inner join bb_runsheet rs on rs.movement_id = m.movementid
inner join bb_run r on r.run_id = rs.run_id
where m.mvtstate = 'Active'
order by m.locationid, m.pickupdate
) SampleTable
Where rn = 1