查询数据库表不存在的ID时如何返回对应ID其余字段为null的结果
SQL查询不存在ID时返回固定行实现方案
可以实现,两种常用的兼容绝大多数SQL方言的实现方法如下:
- 方法1:左连接临时表方案(推荐,支持单/多ID批量查询)
先构造包含待查询ID的临时表,和原客户表做左连接,无匹配时自动返回null值,示例代码如下:
如需批量查询多个ID,只需修改临时表构造逻辑即可:-- 单ID查询示例:查询ID=5的客户 SELECT t.target_id AS customer_ID, ct.`customer name`, ct.`customer address` FROM (SELECT 5 AS target_id) t LEFT JOIN customer_table ct ON t.target_id = ct.customer_ID;-- 多ID批量查询示例:查询ID=5、6、7的客户 SELECT t.target_id AS customer_ID, ct.`customer name`, ct.`customer address` FROM ( SELECT 5 AS target_id UNION ALL SELECT 6 UNION ALL SELECT 7 ) t LEFT JOIN customer_table ct ON t.target_id = ct.customer_ID; - 方法2:UNION补全行方案(适合单ID查询场景)
先执行正常查询,再通过NOT EXISTS判断无结果时补全预设的null行,示例代码如下:
两种方法最终都会在ID=5不存在时返回SELECT customer_ID, `customer name`, `customer address` FROM customer_table WHERE customer_ID = 5 UNION ALL SELECT 5, NULL, NULL WHERE NOT EXISTS ( SELECT 1 FROM customer_table WHERE customer_ID = 5 );5|null|null的结果行,符合需求。
内容的提问来源于stack exchange,提问作者Tarun007
相关产品推荐
相关产品推荐

