如何使用SELECT查询含特殊字符的attributes字段指定记录
解决JSON字段精确匹配查询失败的问题
问题原因
你的attributes字段存储的是JSON类型数据,直接用普通字符串的相等判断逻辑查询会失败,因为数据库会将该字段识别为JSON对象而非纯文本字符串,需要使用对应数据库的JSON处理语法来完成精确匹配。
分数据库解决方案
PostgreSQL
如果attributes是json或jsonb类型,通过类型转换实现精确匹配:
select * from tips_endpoints where description = 'Manual add from SCCM' AND attributes = '{"Our Device": "true"}'::json;
若字段为jsonb类型,更推荐使用jsonb类型转换:
select * from tips_endpoints where description = 'Manual add from SCCM' AND attributes = '{"Our Device": "true"}'::jsonb;
MySQL
针对MySQL的JSON类型字段,使用JSON_EQUAL函数显式对比:
select * from tips_endpoints where description = 'Manual add from SCCM' AND JSON_EQUAL(attributes, '{"Our Device": "true"}');
也可以通过类型转换实现:
select * from tips_endpoints where description = 'Manual add from SCCM' AND attributes = CAST('{"Our Device": "true"}' AS JSON);
SQL Server
如果attributes是NVARCHAR存储的JSON字符串(或原生JSON类型),确保格式完全一致后直接对比:
select * from tips_endpoints where description = 'Manual add from SCCM' AND attributes = '{"Our Device": "true"}';
关键注意点
- 必须保证查询用的JSON字符串与字段存储的JSON格式完全一致,包括空格位置、引号类型(必须是双引号)、键值对顺序(部分数据库严格匹配顺序)。
- 优先使用数据库原生的JSON处理方法,避免直接字符串比较带来的兼容性和稳定性问题。
内容的提问来源于stack exchange,提问作者Rohit
相关产品推荐
相关产品推荐

