我有两张桌子。
表A
id | json
----+------------------
a | {"st":[{"State": "TX", "Value":"0.02"}, {"State": "CA", "Value":"0.2" ...
----+------------------
b | {"st":[{"State": "TX", "Value":"0.32"}, {"State": "CA", "Value":"0.47" ...
表B
idx | state| dir
----+-------+----------
1 | TX | 123
----+-------+----------
2 | CA | 15
我想使用表B中的列temp来过滤表A.而表B将根据idx值选择。
当状态等于从tableB创建的临时表时,我想从每一行中选择值,其中idx是确定的数字
让我们说idx等于2.这意味着我可以使用以下sql查询创建临时表
with tempT AS(
SELECT *
FROM tableB
where idx = 2);
这就是我想要实现的目标
idx | state| value
----+-------+----------
2 | CA | 0.2
----+-------+----------
2 | CA | 0.47
我该怎么做?
答案 0 :(得分:1)
您应该使用jsonb_array_elements之类的:
WITH A AS
(SELECT 'a' AS id,
'{"st":[{"State": "TX", "Value":"0.02"}, {"State": "CA", "Value":"0.2"}]}'::jsonb AS json
UNION SELECT 'b' AS id,
'{"st":[{"State": "TX", "Value":"0.32"}, {"State": "CA", "Value":"0.47"}]}'::jsonb AS json),
B AS
(SELECT 1 AS idx,
'TX' AS state,
123 AS dir
UNION SELECT 2 AS idx,
'CA' AS state,
15 AS dir)
SELECT *
FROM
(SELECT A.id,
jsonb_array_elements(A.json->'st') AS obj
FROM A) AS A
inner JOIN B on B.state = obj->>'State'::text
where B.idx = 2;