In a table like this:
id_fk | valid | val
----------------------
1 | 0 | val1A
1 | 1 | val1B
2 | 0 | val2A
3 | 1 | val3A
3 | 0 | val3B
How dould I select those that are valid=1, or if a valid one does not exist for a id_fk then one that is valid=0?
Basically from this table
id_fk | valid | val
----------------------
1 | 0 | val1A
1 | 1 | val1B
2 | 0 | val2A
3 | 1 | val3A
3 | 0 | val3B
I want to select these (distinct id_fk per row):
id_fk | valid | val
----------------------
1 | 1 | val1B
2 | 0 | val2A
3 | 1 | val3A
Exactly as you describe it:
SELECT *
FROM myTable a
WHERE valid = 1
OR NOT EXISTS
(
SELECT 1
FROM myTable b
WHERE b.id_fk = a.id_fk
AND b.valid = 1
)
Assuming your valid columns having 1 and 0 only :
select * from (SELECT *
FROM Table1 a order by id_fk asc , valid desc) abc
group by id_fk;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.