【问题标题】:MySql convert nested SELECT IN queries into JOINsMySql 将嵌套的 SELECT IN 查询转换为 JOIN
【发布时间】:2017-08-24 15:19:19
【问题描述】:

我读到在 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>&

谢谢

【问题讨论】:

  • 好吧,将第一个查询的输出与您的尝试进行比较,如果结果匹配,那么您做对了。但我认为你的尝试过于复杂了。

标签: mysql sql select join sql-update


【解决方案1】:

试试这个:

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 != &;

【讨论】:

    【解决方案2】:

    在 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=& 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-11
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2017-07-12
      • 2020-01-29
      相关资源
      最近更新 更多