Postgresql -使用like运算符对连接bg 2表进行JSON数据过滤

mklgxw1f  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(129)

我在Postgresql 13的2个表中有JSON数据。我试图使用like操作符连接它们。但是由于字段中的数据是JSON,我得到了一个语法错误。
错误:第6行“DepartmentId”或其附近出现语法错误:... class ='class1 '部门ID'类似于' %e.数据库::'部门ID '类似于'部门ID '类似于'%e.数据库::'部门ID'类似于'部门ID'类似于' % e.数据库::'部门ID '类似于'部门ID '类似于' % e.数据库::'部门ID'类似于'部门ID'类似于' % e.数据库::'部门ID '类似于'部门ID '类似于'%e.数据库::'部门ID'类似于'部门ID'类似于'%e.数据库::'部门ID'类似于'部门ID'类似于' % e.数据库::'部门ID'类似于'部门ID'类似于' % e.数据库::'部门ID'类似于'部门ID'类似于'
SQL FIDDLE for reference
下面是我的疑问:

CREATE SCHEMA dbo;

CREATE TABLE dbo.Emp
(
  EmpId varchar(50),
  json_data varchar
);

INSERT INTO dbo.Emp (EmpId,json_data) values ('E1', '{"EmpId":{"value":"E1","display_value":"E1"},"DepartmentId":{"value":"D1","display_value":"D1"}}')
  ,('E2', '{"EmpId":{"value":"E2","display_value":"E2"},"DepartmentId":{"value":"D2","display_value":"D2"}}');
  
select * from dbo.Emp;

CREATE TABLE dbo.Dept
(
  DeptId varchar(50),
  json_data varchar

);

INSERT INTO dbo.Dept (DeptId, json_data) values ('D1', '{"DeptId":"D1","dv_DeptId":"D1","DeptName":"IT","dv_DeptName":"IT"}}')
  ,('D2', '{"DeptId":"D2","dv_DeptId":"D2","DeptName":"Marketing","dv_DeptName":"Marketing"}}')
  ,('D3', '{"DeptId":"D3","dv_DeptId":"D3","DeptName":"HR","dv_DeptName":"HR"}}');

SELECT * FROM dbo.Dept;

select  
    e.json_data::json->'DepartmentId' ->> 'value' as "Emp_DepartmentId"
  , d.json_data::json->>'dv_DeptId' as "Dept_DepartmentId"
    from dbo.Emp e
    LEFT JOIN dbo.Dept as d
    ON d.json_data::json->>'dv_DeptId' like '%e.json_data::json->'DepartmentId' ->> 'value'%' -- throws syntax error

预期输出

Emp_DepartmentId  Dept_DepartmentId
D1                   D1
D2                   D2
bmvo0sr5

bmvo0sr51#

您可以通过将'%'连接到like语句来稍微改变like语句的构造,这样它就可以工作了。
dbfiddle

select  
   e.json_data::json->'DepartmentId' ->> 'value' as "Emp_DepartmentId"
   , d.json_data::json ->> 'dv_DeptId' as "Dept_DepartmentId"
    from dbo.Emp e
    LEFT JOIN dbo.Dept as d
    ON d.json_data::json ->> 'dv_DeptId' like '%' || cast(e.json_data::json->'DepartmentId' ->> 'value' as varchar) || '%'

相关问题