1

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This'll also select rows where Username = 'johndoe' and DeleteByReceiver <> '0', but DeleteBySender = '0'. I don't think that's what the OP wants. You should change the first part of the WHERE clause to (Username <> 'johndoe' AND DeleteBySender = '0')
@Joseph Silber, good point. See update. And thanks for commenting with your down vote.
Not my DV. The OP's needs (which were since updated) hadn't been expressed clearly enough to invalidate this answer, so I didn't downvote. Thought a comment would be more constructive.
@Joseph Silber, fair enough. I imagine they had the same point as you.
4
SELECT 
    Username, 
    Message
FROM Mail
WHERE (IF(Username='johndoe',DeleteByReceiver = 0,DeleteBySender =0))
LIMIT 1

Comments

0
SELECT Username, Message
FROM Mail
WHERE (Username = 'johndoe' AND DeleteByReceiver='0') OR DeleteBySender = '0'
LIMIT 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.