I want to execute 2nd query if first query return no result. I want to get those id age > 20. If no result, want to get number of id with age < 20.
In table:
id name gender age
1 'Ryan' 'M' 30
2 'Joanna' 'F' 10
query
(SELECT id FROM students WHERE age > 20
ORDER BY id desc limit 1)
UNION ALL
SELECT count(id) FROM students WHERE age < 20 AND
NOT EXISTS (SELECT * FROM students WHERE age > 20 ORDER BY id desc limit 1)
result :
id
1
0
It should return 1 only but return 1 and 0.
If change ryan age to 10, it return 2 which is correct.
Link :query
2
Answers
UNION ALL
is conjunction of queries in terms of running all queries before and after the keyword.your request could be done by using stored procedure where you can add condition to check if it needs to execute the second query.
Here you go;
As you asked for case 1: list of id’s limit 1 and case 2: count.
This should work!!!
Result 1: Insert statement with age > 20 and one for age < 20
Result 2 All inserts which age < 20