質問

I am using MySQL and stuck with - i guess simple issue. It looks like this:

I have a table:

-----------------
id | name | age 
-----------------
1  | abc  | 0
2  | cde  | 30
3  | abc  | 30
4  | efg  | 0

Now, i want to select name and age but select all of them with upcoming condition: if there is any row with age 30 select it, otherwise select those with age 0. if there is both 30 and 0 age (like in example above) select only one row with age = 30. if there is only row with age = 0 - select it.

Using table from above i want to have result like this:

id | name | age 
-----------------
2  | cde  | 30
3  | abc  | 30
4  | efg  | 0

Mysql should ignore first row with age 0 because there is row with the same name but age = 30. I tried

SELECT name, age FROM table WHERE CASE WHEN age = 30 THEN 1 ELSE age = 0 END

But it selects multiple rows with both 0 and 30 age. Hope you can help me.

役に立ちましたか?

解決

not sure if this is exactly what you are looking for but test it and see if it works :)

(SELECT id, name, age FROM myTable WHERE age = 30)

UNION

(SELECT id, name, age FROM myTable WHERE age = 0 ORDER BY id DESC LIMIT 1)

SQL FIDDLE to play with

(SELECT id, name, age FROM myTable WHERE age = 30)

UNION

(SELECT id, name, age
FROM mytable
WHERE age = 0
  AND name NOT in(SELECT name FROM myTable WHERE age = 30)
ORDER BY id DESC)

NEW FIDDLE with op requests

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top