1

I'd like to create a query like that looks up a value from another table if the value of a particular field is not 0. Like this?

SELECT id, name, type, site_id
   IF (site_id > 0)
     THEN (SELECT id FROM setups WHERE setups.id = image.site_id) as site
     ELSE "" as site
FROM image
  ORDER BY image.id

Can someone help me with the syntax for doing the SELECT in the middle, only if the value of site_id is not 0 and based on the value of site_id. If the site_id = 0, I need return an empty string.

Thanks!

2 Answers 2

3

You can do this with a correlated subquery and a case (which I prefer to the if function):

SELECT i.id, i.name, i.type, i.site_id,
       (CASE WHEN i.site_id > 0
            THEN (SELECT s.id FROM setups s WHERE s.id = i.site_id)
            ELSE ''
        END) as site
FROM image i
ORDER BY i.id
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Gordon. Most helpful, unfortunately I have struck another problem I need to get my head around. I will be back . :)
0

if you need the related id from setups i recommend:

SELECT `image`.`id`, `image`.`name`, `image`.`type`, `setups`.`id` as site_id FROM `image`, `setups` WHERE `setups`.`id`=`image`.`site_id`

If site_id is 0 its will be descarted, only the matching rows will be showed, the subqueries are very slow compared whit joins

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.