选择满足2个条件的计数?

时间:2010-11-16 16:02:14

标签: sql operators subquery

Select count(*) from Merchant where Email in 
(Select SentEmail from MerchantInvitations where MerchantID = '16092') AND 
CreatedOn>  (Select TimeSent from MerchantInvitations where MerchantID = '16092')

我希望商家的计数满足其电子邮件位于MerchantInvitations的SentEmail列中 和CreatedOn> MerchantInvitations中的时间表。但我得到一个错误,“子查询返回超过1的值。这是子查询时允许的 follow =,!=,<,< =等等或当子查询用作表达式时“请帮帮我!!提前致谢!

6 个答案:

答案 0 :(得分:2)

MerchantID ='16092'的MerchantInvitations中的多个条目会导致此问题。也许你想要最新的TimeSent,如下:

Select count(*) from Merchant where Email in 
(Select SentEmail from MerchantInvitations where MerchantID = '16092') AND 
CreatedOn>  (Select MAX(TimeSent) from MerchantInvitations where MerchantID = '16092')

答案 1 :(得分:1)

如果你的第二个子查询返回多行,它将永远不会工作。但是,您可以使用ANY或ALL关键字:

SELECT COUNT(*)
FROM Merchant
WHERE Email IN (SELECT SentEmail
               FROM MerchantInvitations
               WHERE MerchantID = '16092') -- Why not 16092? Is it really a string?
AND CreatedOn > ANY (SELECT TimeSent
                     FROM MerchantInvitations
                     WHERE MerchantID = '16092');

但看起来你只想做一个简单的连接:

SELECT COUNT(*)
FROM Merchant M
INNER JOIN MerchantInvitations I
    ON M.MerchantID = I.MerchantID -- You may have to change this
    AND M.Email = I.SentEmail
    AND M.CreatedOn > I.TimeSent
WHERE M.MerchantID = 16092;

哪个肯定比你的子查询更快。

答案 2 :(得分:0)

您的子查询似乎返回了多个与TimeSent进行比较的CreatedOn。要解决此问题,请添加ALL说明符:

Select count(*) from Merchant where 
Email in (Select SentEmail from MerchantInvitations where MerchantID = '16092') AND 
CreatedOn > ALL (Select TimeSent from MerchantInvitations where MerchantID = '16092')

答案 3 :(得分:0)

问题可能是

 (Select TimeSent from MerchantInvitations where MerchantID = '16092')

如果该子查询返回多个值,那么数据库引擎如何知道与CreatedOn进行比较?

您可以在子查询中使用MIN(TimeSent)或MAX(TimeSent)(代替TimeSent),以适当的方式解决问题。

答案 4 :(得分:0)

使用where而不是

Select count(*) from Merchant where exists
(Select SentEmail from MerchantInvitations where MerchantID = '16092' and MerchantInvitations.sentemail = merchant.email) AND 
CreatedOn>  (Select TimeSent from MerchantInvitations where MerchantID = '16092' and MerchantInvitations.sentemail = merchant.email)

答案 5 :(得分:0)

使用单个EXISTS子查询:

Select count(*) 
from Merchant M
where exists
(select null
 from MerchantInvitations I
 where M.Email = I.SentEmail AND 
       M.CreatedOn > I.TimeSent AND
       I.MerchantID = '16092')