Select on condition

Asked

Viewed 43 times

1

I have the following example table (tbl_Local) in Mysql:

ID| LOCAL|  COR
1 | A    |RED
2 | A    |RED
3 | B    |RED
4 | B    |BLACK
5 | B    |WHITE
6 | C    |RED
7 | D    |BLUE
8 | E    |BLUE
9 | E    |ORANGE
10| E    |YELLOW
11| E    |RED
12| F    |RED
13| G    |ORANGE
14| G    |BLUE
15| H    |ORANGE

I would like to create a select that returns to me ONLY the places they own EXCLUSIVELY the color RED, that is, if the LOCAL have another COR other than the RED it should not be displayed.

In this table for example the return should be:

    LOCAL|  COR
    A    |RED
    C    |RED
    F    |RED

I tried using the following syntax:

 Select tbl_Local.*, count(distinct(COR)) from tbl_Local where COR = 'RED' Group By LOCAL

But it didn’t work, and I’m out of ideas.

  • SELECT * FROM tbl_Local WHERE COR = 'RED' GROUP BY LOCAL doesn’t work?

  • It does not work, because in this case it will return the location 'E' that has other colors besides 'RED'

1 answer

3


One option is not exists:

Select distinct 
 t.Local,
 t.COR
from tbl_Local t 
Where t.COR = 'RED' 
and not exists (select 1 from tbl_Local x where x.LOCAL = t.LOCAL and x.COR != t.COR);

I took advantage of @Barbetta’s Sqlfiddle: http://sqlfiddle.com/#! 9/82262e/10

Select all where the color is red and there is no same place with different color

  • 1

    Exactly what I was going to comment on

  • 1

    Rovvan confirmed by the information, however, when I execute the instruction I get the following error: Error Code: 1064. You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'select 1 from tbl_Local x Where x.Local = t.Local and x.COR != t. COLOR)' at line 5

  • I was wrong about exists, I got it right

  • 1

    Except Rovann, that’s right! Thank you very much mate! Thanks for the effort also Wees

  • arrange, =] good afternoon

Browser other questions tagged

You are not signed in. Login or sign up in order to post.