IF 在 WHERE 子句中
IF in WHERE clause
del=0 - 未删除,del=1 - 发送者和接收者删除消息,del=2 - 发送者删除消息,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
但是不行。请帮忙
您很可能 运行 遇到 IF()
函数 returns 字符串或数值的问题。但是您似乎期望它 returns 是一个布尔值。 (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 处理
顺便说一句:您真的只想为 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
del=0 - 未删除,del=1 - 发送者和接收者删除消息,del=2 - 发送者删除消息,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
但是不行。请帮忙
您很可能 运行 遇到 IF()
函数 returns 字符串或数值的问题。但是您似乎期望它 returns 是一个布尔值。 (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
.
顺便说一句:您真的只想为 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