2015-12-03 38 views
2

比方说,我有两个表:加入的设置返回函数(json_array_elements)结果与表列

User_Combination

+--------+----------------+ 
| id | combination | 
+--------+----------------+ 
| 6 |  [1, 2]  | 
| 9 |  [2, 3]  | 
+--------+----------------+ 

颜色

+--------+----------------+ 
| id | color  | 
+--------+----------------+ 
| 1 |  Blue  | 
| 2 |  Yellow | 
| 3 |  Green | 
+--------+----------------+ 

我想加盟结果json_array_elements(color)与元素的id。例如,

select json_array_elements(color) as CombinationID 
from User_Combination where id = 6; 

结果是

+-------------------+ 
| CombinationID | 
+-------------------+ 
| 1    | 
| 2    | 
+-------------------+ 

我无法加入CombinationIDColors.id。当我尝试SQL命令,例如:

select json_array_elements(article_data) AS articlesInOutfits (color) as CombinationID 
from User_Combination uc JOIN Colors co ON co.id = articlesInOutfits; 

select json_array_elements(article_data) AS articlesInOutfits (color) as CombinationID 
from User_Combination uc JOIN Colors co ON co.id = uc.articlesInOutfits; 

它说articlesInOutfits不存在。
有什么建议吗?

+1

你的Postgres的版本? –

+0

使用9.3.3。令人惊讶的是,unnest不起作用。 – NateW

+0

你能解决一些令你困惑的错误吗? 'json_array_elements(color)'? “元素”指的是什么?显示数据类型和约束的实际表格定义会更有用。 –

回答

3

使用unnest()得到解压组合:

select id, unnest(combination) cid 
from user_combination; 

id | cid 
----+----- 
    6 | 1 
    6 | 2 
    9 | 2 
    9 | 3 
(4 rows)  

使用解压cids加入与colors

select u.id, color 
from (
    select id, unnest(combination) cid 
    from user_combination 
    ) u 
join colors c 
on cid = c.id; 

id | color 
----+-------- 
    6 | Blue 
    6 | Yellow 
    9 | Yellow 
    9 | Green 
(4 rows) 

使用聚集函数(如json_agg())即可加入颜色汇总的对于用户:

​​

如果combination的类型是json你应该使用在横向json_array_elements()的加入:

select u.id, json_agg(color) 
from (
    select id, cid 
    from user_combination, 
    lateral json_array_elements(combination) cid 
    ) u 
join colors c 
on cid::text::int = c.id 
group by 1; 
+0

真棒,一秒钟,我会试试看 – NateW

+0

我使用Postgres版本9.3.3,它说:错误:函数unnest(json)不存在 – NateW

+0

啊我看到了,我存储一个数组作为类型JSON。我会解决这个问题,然后尝试unnest – NateW