我想在给出id
后从行中获取所有字段,但如果表中没有指定id
的行,那么我想返回“不存在”或其他内容。我在一个查询中需要这个。
最佳答案
我只能想到这个解决方案:
(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 来解决这个任务?用您使用的编程语言替换默认值不是更容易吗(我希望)?
关于mysql - 返回表中的所有字段或返回一个查询中不存在的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32582896/