say I have the following simple table
table a { id int, pointId int, state int, value int }
id pointId state value
-------------------------------
1 1 2 xxxxx
2 3 2 xxxxx
3 3 2 xxxxx
4 3 1 xxxxx
with the following two queries:
SELECT * FROM a WHERE state = 1 and pointId = x
SELECT * FROM a WHERE state = 2 and pointId = x
Is there a way to combine the two queries so that:
- if query 1 returns >0 rows, it returns the result from query 1
- if query 1 returns 0 rows, it returns the result from query 2
(so for pointId = 1 it would return row 1, for pointId = 3 it would return row 4)
I've been trying to combine the two with a union doing something like
SELECT * FROM a WHERE state = 1 AND pointId = x
UNION ALL
SELECT * FROM a WHERE state = 2 AND pointId = x and
pointId NOT IN (SELECT pointId FROM a WHERE state = 1 AND pointId = x)
I'm wondering if I'm making this way to complicated and if there's a more easy way. I realize I could just run the first query and then handle it in my code, but it would be really nice if I could do this in the sql. Any advice or pointers would be great!
Thanks,
A
EXISTS.