MySql:如果在函数内部或外部调用,则相同的select count(*)查询返回不同的结果

时间:2014-07-12 14:33:57

标签: mysql count

嗯,就这么简单。以下查询返回1:

select count(*) as Total from conversations
where TargetUserID = 2
  and LastMessageSenderUserID = StarterUserID
  and TotalMessages > 0
  and Answered = 0
  and (@ReadDate := GetConversationReadDate(ID)) is not null
  and @ReadDate < date_sub(now(), interval 1 day)

我使用一个参数user_id复制了存储函数体中的相同代码:

return (select count(*) as Total from conversations
where TargetUserID = user_id
  and LastMessageSenderUserID = StarterUserID
  and TotalMessages > 0
  and Answered = 0
  and (@ReadDate := GetConversationReadDate(ID)) is not null
  and @ReadDate < date_sub(now(), interval 1 day))

然而,后者(使用user_id = 2调用)返回0.它不是确定性的并且标记为“读取sql数据”。

1 个答案:

答案 0 :(得分:1)

您在where子句的两个部分中使用相同的变量。这不安全。 MySQL不保证where子条款的执行顺序。你应该做点什么:

and GetConversationReadDate(ID) < date_sub(now(), interval 1 day))

如果返回的值为NULL,则会自动失败,因此NULL检查是多余的。

以下是documentation

的引用
  

作为一般规则,除了在SET语句中,你永远不应该   为用户变量赋值并读取其中的值   言。