假设我们有这个人表
id name gender
1 John male
2 Kurt male
3 Tyler male
4 Matthias male
我们有这个查询
SELECT * FROM person WHERE gender = female
将返回空
如果当前查询返回为空,是否有一种方法可以在MySQL(在SQL中)运行并返回备用查询的结果?
类似于“如果没有返回任何行,则返回性别为=男性的行”
答案 0 :(得分:2)
请注意,这仅适用于存储过程和函数,因为IF THEN / ELSE
语句处理。
IF EXISTS (SELECT 0 FROM person WHERE gender = female) THEN
SELECT * FROM person WHERE gender = female
ELSE
SELECT * FROM person WHERE gender = male
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html