我有一个表,其中有一列具有 JSON 值。此栏目过于拥挤,无法从栏目中获取详细信息。
Company User
A [{"Name":"Mark","email":"mark.com","password":"password"},{"Name":"Keith","email":"Keith.com","password":"password"}]
B [{"Name":"Anna","email":"anna.com","password":"password"},{"Name":"Lewis","email":"Lewis.com","password":"password"}]
C [{"Name":"Bill","email":"bill.com","password":"password"},{"Name":"Stuart","email":"stuart.com","password":"password"}]
有什么方法可以在 select 语句中打破如下所示的列
Company User_1_name User_1_email User_1_password User_2_name User_2_email User_2_password
A Mark mark.com password Keith Keith.com password
B Anna anna.com password Lewis Lewis.com password
C Bill bill.com password Stuart stuart.com password
最佳答案
由于根据您的评论,该列未定义为 jsonb
或 json
,因此您需要进行强制转换才能使其正常工作:
select company,
(user::jsonb)->0->>'Name' as user_1_name,
(user::jsonb)->0->>'email' as user_1_email,
(user::jsonb)->0->>'password' as user_1_password,
(user::jsonb)->1->>'Name' as user_2_name,
(user::jsonb)->1->>'email' as user_2_email,
(user::jsonb)->1->>'password' as user_2_password
from your_table;
如果每行的用户数量有所不同,那么您将需要添加尽可能多的列以捕获最大大小。
如果任何行的 user
列中包含无效的 json,则此操作将不起作用。
关于json - 在 postgresql 中拆分 JSON 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63486197/