2

I have the following query:

  SELECT `users`.`id`, `login`, `fullname`, `active`, `sex`, `height`,
  `special-title`, `language`, `body-fat`,
  `main-photo-id`, `main-photo-offset`, `weight`,
  `objective`, `level`, `config-comments-type`,
  (
     SELECT `type`
     FROM `users-pro`
     WHERE
        (`user` = `users`.`id`)
        AND
        (`starts` <= $time)
        AND(
           (`ends` > $time)
           OR
           (`ends` IS NULL)
        )
     LIMIT 1
  ) as `account_type`
  FROM `users`

I'm wondering how/where do I add an IF statement, so that if the inner SELECT returns NULL (no entries for the user in users-pro, a value 1 would be returned.

This is what I usually do if there is no subquery:

SELECT IF(`rank` = 1, `rank`, 0) as `rank`

However, I don't know how to do this with a subquery.

1 Answer 1

2

You can use the ANSI standard coalesce() function for this, by wrapping the subquery in it:

SELECT `users`.`id`, `login`, `fullname`, `active`, `sex`, `height`,
  `special-title`, `language`, `body-fat`,
  `main-photo-id`, `main-photo-offset`, `weight`,
  `objective`, `level`, `config-comments-type`,
  coalesce((
     SELECT `type`
     FROM `users-pro`
     WHERE
        (`user` = `users`.`id`)
        AND
        (`starts` <= $time)
        AND(
           (`ends` > $time)
           OR
           (`ends` IS NULL)
        )
     LIMIT 1
  ), 1) as `account_type`
  FROM `users`
Sign up to request clarification or add additional context in comments.

3 Comments

That seems like a solution, yeah. I'm wondering whether there are no more options for this, but I think I should accept it.
Although COALESCE will work fine, I believe the most appropriate function from a logical standpoint is IFNULL since it returns another value in case an expression is NULL. Just to clarify: COALESCE accepts multiple arguments and returns the first non-NULL value.
@setsuna . . . I have a strong preference for using ANSI standard constructs instead of database-specific ones, which is why I generally prefer coalesce().

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.