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

标签 mysql

我想在给出id后从行中获取所有字段,但如果表中没有指定id的行,那么我想返回“不存在”或其他内容。我在一个查询中需要这个。

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

最佳答案

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

(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/

相关文章:

mysql - MySQL 查询的等效 MemSQL 查询

mysql - 巨大的 MySQL 随机字母数字字符串

python - 如何从flask-SQLAlchemy 查询SQL View

mysql:获得最佳答案

mysql - sap hana 中的 case when 语句

php - 我正在尝试使用 php 建立一个简单的登录系统。它会运行,但您也可以使用错误的凭据登录。我究竟做错了什么?

mySQL 查看行是否存在

php - 如何创建一个始终运行的 PHP 后台脚本来清理 mySql 数据库中的特定行?

php - 上传文件并设置权限

mysql - 按到期日期对赠款进行排序