5

I have a table like this:

projectName | info
--------------------
     all    | i1
     all    | i2
     all    | i3
     name1  | i4
     name1  | i5
     all    | i6

I have a query that checks the project name. If it exists in the table, I have to select only the information regarding that specific project. If it does not exist, I must get the information for 'all' projects.

For example, if I my entry is 'name1', my output should be:

i4
i5

If my entry is 'name2', my output should be:

i1
i2
i3
i6

Is there a way I can do this in a mysql query? I looked for examples but everything I found was about retrieving information from two different tables.

2
  • Why do you need to do this in a MySQL query? This would probably be easier to do within your application. Commented Apr 18, 2017 at 14:15
  • @JeffersonLima I just got curious about it, actually. I'll do it within my application if I can't work this out. Commented Apr 18, 2017 at 14:43

2 Answers 2

4

One way is to use UNION ALL:

SELECT info
FROM mytable
WHERE projectName = 'name1'

UNION ALL

SELECT info
FROM mytable
WHERE projectName = 'all' AND 
      NOT EXISTS (SELECT 1
                  FROM mytable
                  WHERE projectName = 'name1')

Demo here

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

Comments

3
select * from projects
where projectName = case when exists (select * from projects where projectName = 'name1')
    then 'name1'
    else 'all'
end

3 Comments

but you are outputing the project name instead of project info
@dsharew I'm outputting all columns select *. You can still select any column you want from the table.
got it very nice solution

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.