我有这个简单的(实际上我正在简化实例)SQL命令:
SELECT Username, Message
FROM Mail
WHERE DeleteBySender = '0'
LIMIT 1
但出于某种原因,我有特殊情况,那就是:
IF Mail.Username ='johndoe',WHERE子句不再 DeleteBySender = '0'
,但 DeleteByReceiver = '0'
。< / p>
简而言之,如何基于Mail.Username结果制作动态WHERE子句?
可以用单个SQL命令完成吗?因为如果没有,在我的实际情况中,它将导致PHP脚本更复杂。
**更新:我真正期待的是,用简单的英语: 如果Mail.Username不是johndoe,SQL命令将是这样的:
SELECT Username, Message
FROM Mail
WHERE DeleteBySender = '0'
LIMIT 1
但是如果Mail.Username是johndoe,SQL命令将是这样的:
SELECT Username, Message
FROM Mail
WHERE DeleteByReceiver = '0'
LIMIT 1
答案 0 :(得分:4)
SQL中的解决方案,利用OR
子句分解逻辑,如下所示:
SELECT Username, Message
FROM Mail
WHERE (Username != 'johndoe' AND DeleteBySender = '0')
OR (Username = 'johndoe' AND DeleteByReceiver = '0')
LIMIT 1
注意: LIMIT 1
令人担忧。在不知道您的数据集的情况下,这可能会返回多个结果。你需要测试。
答案 1 :(得分:3)
SELECT
Username,
Message
FROM Mail
WHERE (IF(Username='johndoe',DeleteByReceiver = 0,DeleteBySender =0))
LIMIT 1
答案 2 :(得分:0)
SELECT Username, Message
FROM Mail
WHERE (Username = 'johndoe' AND DeleteByReceiver='0') OR DeleteBySender = '0'
LIMIT 1