我们可以用连接替换嵌套子查询吗 - SQL

Can we replace nested sub-queries with joins - SQL

目前我们正在使用以下嵌套查询来获取特定结果。查询给了我正确的结果,但问题是它需要更多的时间来执行(大约 2 秒来获取 9 条记录)。 table 中的记录:

Table      |  Number of Records
-------------------------------
Account          284
AccountUser       34
AccountCustomer  256
AccountGroup      96

以下是我的查询:

SELECT * FROM Account  where (SomeID = 'XXXXX-XXXXX-XXXXX') and  AccountID  IN  
(SELECT AccountID   FROM AccountUser WHERE SomeID = 'XXXXX-XXXXX-XXXXX' AND AccountID IN  
(SELECT AccountID   FROM AccountCustomer WHERE SomeID = 'XXXXX-XXXXX-XXXXX' AND isDeleted = 0  AND someOtherID IN 
(SELECT someOtherID FROM AccountGroup   WHERE AccountGroupID = 'YYYY-YYYYY-YYYY' AND AccountGroup.SomeID = 'XXXXX-XXXXX-XXXXX' AND AccountID NOT IN  
(SELECT AccountID   FROM AccountGroup WHERE AccountGroupID = 'YYYY-YYYYY-YYYY' AND AccountGroup.SomeID = 'XXXXX-XXXXX-XXXXX'))))

我认为联接会提供更好的性能(如果我错了请纠正我),因此用联接替换了嵌套查询但它没有给我预期的结果。加入查询如下:

SELECT a.* FROM Account a
Inner join AccountUser b on a.AccountID = b.AccountID
Inner join AccountCustomer c on c.AccountID = a.AccountID 
Inner join AccountGroup d on d.AccountID = a.AccountID 
Inner join AccountGroup e on e.AccountID = a.AccountID 
WHERE a.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      b.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      c.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      c.isDeleted = 0 and d.AccountGroupID = 'YYYY-YYYYY-YYYY' and
      d.SomeID = 'XXXXX-XXXXX-XXXXX' and
      e.AccountGroupID ='YYYY-YYYYY-YYYY'

谁能告诉我查询中的联接构造有什么问题。

我发现了两个问题。

  1. 列名错误

    isDeleted = 0 更改为 c.isRelated = 1

  2. 连接 d 和 e 的错误子句

    并且帐户 ID 不在

Inner join AccountGroup d on d.AccountID = a.AccountID 

应该是

Inner join AccountGroup d on d.someOtherID = a.AccountID 

?

试试这个

SELECT distinct a.* FROM Account a
Inner join AccountUser b on a.AccountID = b.AccountID
Inner join AccountCustomer c on c.AccountID = a.AccountID 
Inner join AccountGroup d on d.someOtherID = c.someOtherID 
WHERE a.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      b.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      c.SomeID = 'XXXXX-XXXXX-XXXXX' and 
      c.isDeleted = 0 and d.AccountGroupID = 'YYYY-YYYYY-YYYY' and
      d.SomeID = 'XXXXX-XXXXX-XXXXX' and
      d.AccountID  not in 
(SELECT AccountID   FROM AccountGroup WHERE AccountGroupID = 'YYYY-YYYYY-YYYY' AND AccountGroup.SomeID = 'XXXXX-XXXXX-XXXXX')

除了使用 JOIN,您还可以考虑使用 WHERE EXISTS 或 WHERE NOT EXISTS 来代替丑陋的 IN 语句。与使用 IN 语句检索到的行相比,连接有时可以多 return 行。从查询中我看到您只需要来自帐户 table 的数据,因此 EXISTS 似乎是更合乎逻辑的方式。