del = 0 - 未删除,del = 1 - 发件人和收件人已删除邮件,del2 - 发件人已删除邮件,del = 3 - 收件人已删除邮件。我的代码是:
SELECT
*
FROM
messages
WHERE
(`from` = :owner AND `to` = :partner) OR (`from` = :partner AND `to` = :owner) AND IF(`from` = :owner,`del`=3 OR `del`=0,`del`=2 OR `del`=0)
ORDER BY
id DESC
但它不起作用。请帮助。
答案 0 :(得分:0)
很可能你遇到了IF()
函数返回字符串或数值的问题。但是你似乎期望它返回一个布尔值。 (SQL没有布尔数据类型。)
所以你必须使用IF()
的替代方法:
SELECT
*
FROM
messages
WHERE
(`from` = :owner AND `to` = :partner)
OR (`from` = :partner AND `to` = :owner)
AND (`from` = :owner AND `del` IN (0, 3)
OR `from` <> :owner AND `del` IN (0, 2))
ORDER BY
id DESC
如果from
和:owner
不能为NULL,则应该相同。否则from <> :owner
需要一些NULL处理。
BTW。:你真的只想为OR表达式的第二部分测试del
标志吗?因为这就是SQL如何评估它(AND之前的OR)。
<强>更新强>
从您的评论中,我必须假设评估顺序确实是错误的。因此,我正在改变它:
SELECT
*
FROM
messages
WHERE
(
(`from` = :owner AND `to` = :partner)
OR (`from` = :partner AND `to` = :owner)
)
AND (`from` = :owner AND `del` IN (0, 3)
OR `from` <> :owner AND `del` IN (0, 2))
ORDER BY
id DESC