I have this simple (actually I'm simplifying the real case) SQL command :
SELECT Username, Message
FROM Mail
WHERE DeleteBySender = '0'
LIMIT 1
but for some reason, I have special condition, that is : IF Mail.Username = 'johndoe' then the WHERE clause is not DeleteBySender = '0'
anymore, but DeleteByReceiver = '0'
.
in short, how to make dynamic WHERE clause based on Mail.Username result?
can it be done with single SQL command? because if not, in my real case, it will cause PHP scripting more complex.
**UPDATE : what I really expect, in plain English : if Mail.Username NOT johndoe, SQL command will be like this :
SELECT Username, Message
FROM Mail
WHERE DeleteBySender = '0'
LIMIT 1
but if Mail.Username IS johndoe, SQL command will be like this :
SELECT Username, Message
FROM Mail
WHERE DeleteByReceiver = '0'
LIMIT 1
A solution in SQL utilizing an OR
clause to break up your logic as follows:
SELECT Username, Message
FROM Mail
WHERE (Username != 'johndoe' AND DeleteBySender = '0')
OR (Username = 'johndoe' AND DeleteByReceiver = '0')
LIMIT 1
Note: The LIMIT 1
is concerning. Without knowing your dataset, this may return more than one result. You need to test.
SELECT
Username,
Message
FROM Mail
WHERE (IF(Username='johndoe',DeleteByReceiver = 0,DeleteBySender =0))
LIMIT 1
SELECT Username, Message
FROM Mail
WHERE (Username = 'johndoe' AND DeleteByReceiver='0') OR DeleteBySender = '0'
LIMIT 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.