1

I want to perform a mySQL query that returns all the results in a table but has an additional column that has values "selected" if they correspond to a separate query. For example

| name |
|------|
| a    |
| b    |
| c    |

I want to be able to return the following when I do a query "select * from table where name = 'a';

| name | selected |
|------|----------|
| a    |  yes     |
| b    |          |
| c    |          |

That is, I also want to know which ones where left out.

Rio
  • 14,182
  • 21
  • 67
  • 107

3 Answers3

2
select *
    , selected = case
        when exists (
            select *
            from table2 t2
            where t2.field = t1.field
                and ...etc.
        ) then 1 
        else 0
    end
from table t1
Dan Roberts
  • 4,664
  • 3
  • 34
  • 43
1

Where clause restricts your row set so you get only rows with name 'a'. To get all of them either join the limited table back to itself or use IF without where:

SELECT *, IF( name='a', 'yes', '') AS selected
FROM table
piotrm
  • 12,038
  • 4
  • 31
  • 28
0

The one that worked for me was:

select a.*
    , name = case
        when 
           a.name = 'a'
         then 0 
        else 1
    end
as selected
from points as a
Rio
  • 14,182
  • 21
  • 67
  • 107