我希望在提供id
之后获取行中的所有字段,但如果表格中没有指定id
的行,那么我想要返回'不存在'或者其他的东西。我在一个查询中需要这个。
答案 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解决此任务?在您使用的编程语言中替换默认值是不是更容易(我希望)?