返回表中的所有字段或返回一个查询中不存在的字段

时间:2015-09-15 09:48:40

标签: mysql

我希望在提供id之后获取行中的所有字段,但如果表格中没有指定id的行,那么我想要返回'不存在'或者其他的东西。我在一个查询中需要这个。

http://sqlfiddle.com/#!9/0afa50

1 个答案:

答案 0 :(得分:0)

我只能想到这个解决方案:

(SELECT * FROM `new_table` WHERE id = 1)
UNION 
(SELECT 'not exists!' AS id, 'not exists!' AS name, 'not exists!' AS surname, 'not exists!' AS anotherfield 
 FROM new_table 
 WHERE NOT EXISTS (SELECT * FROM `new_table` WHERE id = 1)
);
+----+------+---------+--------------+
| id | name | surname | anotherfield |
+----+------+---------+--------------+
| 1  | aaa  | ssss    | adad         |
+----+------+---------+--------------+
1 row in set (0,00 sec)

(SELECT * FROM `new_table` WHERE id = 0) 
UNION 
(SELECT 'not exists!' AS id, 'not exists!' AS name, 'not exists!' AS surname, 'not exists!' AS anotherfield         
 FROM new_table         
 WHERE NOT EXISTS (SELECT * FROM `new_table` WHERE id = 0)        
);
+-------------+-------------+-------------+--------------+
| id          | name        | surname     | anotherfield |
+-------------+-------------+-------------+--------------+
| not exists! | not exists! | not exists! | not exists!  |
+-------------+-------------+-------------+--------------+
1 row in set (0,00 sec)

更新:如你所见,这非常难看。为什么需要通过SQL解决此任务?在您使用的编程语言中替换默认值是不是更容易(我希望)?

相关问题