我有一个表,它有一个列,其中的字符串格式如下:{1,4,5}
。它们可以是任意长度,并且我想针对ID在该字符串中的任何值连接一个ID表。
这是第一张表
name id count
apple {1,3,6} 5
orange {5,3,1} 3
potato {8,1,9} 3
这是第二张表-
id2 category
1 foo
2 foobar
3 candy
4 candybar
5 oreo
6 pistachio
我想为第一个表中列出的具有第二个表中的类别的每个ID都占一行。我想让它们看起来像这样-
id2 name id count
1 apple {1,3,6} 5
1 orange {5,3,1} 3
1 potato {8,1,9} 3
3 apple {1,3,6} 5
3 orange {5,3,1} 3
8 potato {8,1,9} 3
9 potato {8,1,9} 3
这就是我到目前为止所得到的。我可以有一个显示为join if the value is included
的联接过滤器吗?
select id2, name, id, count
from table2 as t2
left join table1 as t1
on t2.id2 %in% t1.id
发布于 2019-03-20 07:13:00
当我第一次开始解决这个问题时,我没有看到PostgreSQL。
您可以尝试执行以下操作,但不能保证Postgre不具备所有功能。
SELECT * FROM (
SELECT
Split.a.value('.', 'VARCHAR(100)') AS ID2
,A.Name, A.ID, A.[Count]
FROM
(
SELECT Name, [Count], ID,
CAST ('<M>' + REPLACE(REPLACE(REPLACE(ID,'{',''),'}',''), ',', '</M><M>') + '</M>' AS XML) AS Data
FROM [StackOver].[dbo].[SplitKey]
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
) as B
Left Join [StackOver].[dbo].[SplitKeyID2] as C
On B.ID2 = C.ID2
Where C.Category > ''
Order By B.ID2, B.name
发布于 2019-03-20 07:13:45
我非常确信有一个不涉及GROUP BY
和ARRAY_AGG()
的更好的解决方案,但是既然您已经在那里了,我认为这个查询可能会对您有所帮助:
select
t2.id2,
t2.category,
t1.id,
t1.count
from table1 t1
join table2 t2 on (
position ('{' || t2.id2 || '}' in t1.id) <> 0
or position ('{' || t2.id2 || ',' in t1.id) <> 0
or position (',' || t2.id2 || ',' in t1.id) <> 0
or position (',' || t2.id2 || '}' in t1.id) <> 0
)
https://stackoverflow.com/questions/55251046
复制相似问题