0

I have a table (a) that contains imported data, and one of the values in that table needs to be joined to another table (b) based on that value. In table b, sometimes that value is in a comma separated list, and it is stored as a varchar. This is the first time I have dealt with a database column that contains multiple pieces of data. I didn't design it, and I don't believe it can be changed, although, I believe it should be changed.

For example:

Table a:

column_1 
12345
67890
24680
13579

Table b:

column_1
12345,24680
24680,67890
13579
13579,24680

So I am trying to join these table together, based on this number and 2 others, but when I run my query, I'm only getting the one that contain 13579, and none of the rest.

Any ideas how to accomplish this?

4

1 回答 1

3

将列表存储为逗号分隔的数据结构是设计不佳的标志,尤其是在存储 id 时,id 可能是其本机格式的整数。

有时,这是必要的。这是一个方法:

select *
from a join
     b
     on ','+b.column_1+',' like '%,'+cast(a.column_1 as varchar(255))+',%'

这不会执行得特别好,因为查询不会利用任何索引。

这个想法是将定界符 ( ,) 放在b.column_1. 列中的每个值前后都有一个逗号。a.column_1然后,您可以在附加逗号的情况下搜索匹配项。逗号确保10不匹配100

如果可能,您应该考虑另一种表示数据的方法。如果您知道最多有两个值,则可以考虑在a. 不过,一般来说,您会有一个“连接”表,每对都有一个单独的行。

于 2013-06-05T20:08:54.177 回答