当前,我们正在使用以下嵌套查询来获取特定结果。该查询为我提供了正确的结果,但是问题在于执行时间更长(大约2秒钟来提取9条记录)。表中的记录:
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'))))
我认为Joins会提供更好的性能(如果我错了,请纠正我),因此将嵌套查询替换为joins,但它没有给我预期的结果。已加入查询,如下所示:
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'
有人可以告诉我查询中Joins的构造是什么问题。
答案 0 :(得分:2)
尝试一下
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')
答案 1 :(得分:0)
我可以找到两个问题。
列名错误
isDeleted = 0更改为c.isRelated = 1
连接d和e的子句错误
AND AccountID NOT
答案 2 :(得分:0)
@IBAction func SliderValueChanged(_ sender: UISlider) {
showValueSlider.text = String(format: "The value is:%i",Int(sender.value))
}
应该是
Inner join AccountGroup d on d.AccountID = a.AccountID
?
答案 3 :(得分:0)
除了使用JOIN之外,您还可以使用WHERE EXISTS或WHERE NOT EXISTS代替丑陋的IN语句。联接有时可以返回比用IN语句检索的行更多的行。从查询中我看到您只需要帐户表中的数据,所以EXISTS似乎是更合乎逻辑的方法。