MySql将嵌套的SELECT IN查询转换为JOIN

时间:2017-03-30 15:32:55

标签: mysql sql select join sql-update

我读到在MySql查询中使用IN导致性能下降,这与Oracle不同,应该使用JOIN代替。我能够转换简单的查询,但我正在努力处理包含嵌套SELECT的更复杂的查询。例如:

update Records set ActiveStatus=0, TransactionStatus=0, LastUpdated=& 
where ActiveStatus!=5 and LastUpdated!=& 
and Pk in (select RecordPk from GroupRecordLink 
where GroupPk in (select Pk from Groups where ActiveStatus!=5 and 
DateTimeStamp>&))

我按照this post 进行了重写,但我不确定我的结果是否正确。

update Records r join (select distinct RecordPk from GroupRecordLink grl join 
Groups g on grl.Pk = g.Pk where g.ActiveStatus!=5 and g.DateTimeStamp>&) s
using (Pk) set ActiveStatus=0, TransactionStatus=0, LastUpdated=&  
where ActiveStatus!=5 and DateTimeStamp>&

由于

2 个答案:

答案 0 :(得分:0)

在Mysql中,您可以使用显式联接进行更新(您必须更改&以及正确的值)

    update Records 
    INNER JOIN GroupRecordLink on GroupRecordLink.RecordPk = Records.PK
    INNER JOIN Groups on ( GroupRecordLink.GroupPk = Groups.Pk 
                  and  Groups.ActiveStatus!=5
                         and Groups.DateTimeStamp>&)
    set ActiveStatus=0, 
    TransactionStatus=0, 
    LastUpdated=& 

答案 1 :(得分:0)

试试这个:

UPDATE Records 
INNER JOIN GroupRecordLink ON Records.Pk = GroupRecordLink.RecordPk 
INNER JOIN Groups ON GroupRecordLink.GroupPk = Groups.Pk AND Groups.ActiveStatus != 5 
SET Records.ActiveStatus = 0, 
    Records.TransactionStatus = 0, 
    Records.LastUpdated = & 
WHERE Records.ActiveStatus != 5 
  AND Records.LastUpdated != &;