Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select records from table if certain value exists, if not, select other records

Tags:

mysql

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.

like image 351
Bizzys Avatar asked Apr 18 '17 14:04

Bizzys


Video Answer


1 Answers

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

like image 95
Giorgos Betsos Avatar answered Oct 19 '22 23:10

Giorgos Betsos