TNK
TNK

Reputation: 4333

Check 2 fields in a select query

I have a mysql table named 'members'.

MEMBERS | member_id, username, email, password, domain_name

email field couldn't be NULL but domain_name could be.

Here I want to make a SELECT Query to get username and email or domain_name. If domain_name exist for a particular member_id then I don't need to select email. If not I need to get email.

This is my query I am using at this time. But It select both email and domain.

SELECT email, username, domain_name 
FROM members
ORDER BY username DESC; 

Can anybody help me to update this select query? Thank You.

Upvotes: 1

Views: 88

Answers (2)

Samosa
Samosa

Reputation: 845

You can use the IF function in mysql

SELECT `username`, 
IF(`domain_name` IS NULL ,`email`, `domain_name`) as `email_or_domain` 
FROM `members`

The syntax of the MySQL IF function is:

IF(expr,if_true_expr,if_false_expr)

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64496

You can use CASE

SELECT 
  username,
  CASE
    WHEN domain_name IS NULL 
    THEN email 
    ELSE domain_name 
  END your_alias 
FROM
  members 
ORDER BY username DESC ;

your_alias could be any name you want to specify as a column it can be email or domain_name

Upvotes: 3

Related Questions