需要建议在表1中拆分字符串,将其ID与表2匹配并连接值。
表 - 1
Id Tbl1Col
1 2
2 2,4
3
4 6
5 3
表 - 2
Id Tbl2Col
1 E
2 F
3 M
4 U
5 P
6 C
7 N
8 G
查询 -
SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id
现在如果@Id = 1
,则输出为F
- 工作正常
现在如果@Id = 2
,则输出应为FU
- 不应为F,U
答案 0 :(得分:1)
呸!但您可以使用LIKE
:
SELECT T2.Tbl2Col
FROM Table1 T1 LEFT JOIN
Table2 T2
WHERE ',' + T1.Tbl1Col + ',' LIKE '%,' + CAST(T2.Id as VARCHAR(255)) + ',%'
WHERE T1.Id = @Id;
您的数据格式很糟糕,因此无法使用索引。你应该有一个单独的表,每个Table1.id
和Table2.id
有一行。这样的表称为联结表或关联表。
答案 1 :(得分:1)
按照下一种方法: -
1)使用CROSS APPLY
XML
2)用左连接加入两个表。
3)通过使用STUFF
&来连接具有相同id的许多行。 FOR XML
4)使用替换功能删除逗号。
<强>演示: - 强>
declare @MyTable table (id int , Tbl1Col varchar(10))
insert into @MyTable values (1,'2'),(2,'2,4'),(3,''),(4,'6'),(5,'3')
declare @MyTable2 table (id int , Tbl2Col varchar(10))
insert into @MyTable2 values (1,'E'),(2,'F'),(3,'M'),(4,'U'),(5,'P'),(6,'C'),(7,'N'),(8,'G')
select a.id , Tbl2Col
into #TestTable
from
(
SELECT A.id,
Split.a.value('.', 'VARCHAR(100)') AS Tbl1Col
FROM
(
SELECT id,
CAST ('<M>' + REPLACE(Tbl1Col, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM @MyTable
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) ) a
left join @MyTable2 b
on a.Tbl1Col = b.id
order by a.id
SELECT id, Tbl2Col =
Replace(STUFF((SELECT DISTINCT ', ' + Tbl2Col
FROM #TestTable b
WHERE b.id = a.id
FOR XML PATH('')), 1, 2, ''),',','')
FROM #TestTable a
GROUP BY id
<强>输出: - 强>
1 F
2 F U
3 NULL
4 C
5 M
参考文献: -
Turning a Comma Separated string into individual rows
How to concatenate many rows with same id in sql?
请勿使用此方法,并将数据库规范化,只需将其用作有趣/训练/尝试....等代码。
答案 2 :(得分:0)
create table dbo.Table01 (
Id int
, Col varchar(100)
);
create table dbo.Table02 (
Id int
, Col varchar(100)
);
insert into dbo.Table01 (Id, Col)
values (1, '2'), (2, '2, 4');
insert into dbo.Table02 (Id, Col)
values (1, 'E'), (2, 'F'), (4, 'U');
select
t.Id
, replace(STRING_AGG (t02.Col, ','), ',', '') as StringAgg
from dbo.Table01 t
cross apply string_split (t.Col, ',') as ss
inner join dbo.Table02 t02 on ss.value = t02.Id
group by t.id