简体   繁体   English

SQL从逗号分隔的字符串中选择查询

[英]SQL select query from comma separated string

I have a table with with column location with values 我有一个表,列的location带有值

row1: sector A, sector B, Sector c
row 2: sector B, sector f, Sector A
row 3: sector f

No I am looking for the sql query to search from these rows with comma separated string say I can search with Sector A, sector f in that case row 1 ,row2, row 3 values should print as Sector A is in row 1, row2 and sector f is in row 3 不,我正在寻找要用逗号分隔的字符串从这些行中搜索的sql查询,说我可以使用Sector A, sector f进行搜索,在这种情况下,行1,行2,行3的值应打印,因为Sector A位于行1,行2和行2。 sector f在第3行

I am trying something like this but matches the exact string only ... 我正在尝试类似的事情,但仅匹配确切的字符串...

SELECT id , name FROM tb1 "+
" where    Charindex(','+cast(location  as     varchar(8000))+',',',"+loc+",') > 0

and loc is sector A,sector f loc是A扇区,f扇区

Instead of having "location" column in your main table with comma separated values, what you really should have is a second table. 您真正应该拥有的是第二张表,而不是在主表中使用逗号分隔值的“ location”列。 I'm going to call your first table inventory_item and assume here you're trying to track the locations where that inventory is located (since you didn't say what your application does). 我将调用您的第一个表stock_item,并假设您在此处尝试跟踪该清单的位置(因为您没有说明应用程序的功能)。

So add a table called inventory_item_location with columns: 因此,添加一个带有列的名为清单库存表的表:

id, inventory_item_id, location id,inventory_item_id,位置

You would have one row per location in that inventory_item_location table and the inventory_item_id would be the id of your inventory_item table. 您在那个stock_item_location表中每个位置只有一行,而库存_item_id将是您的stock_item表的ID。 So then you just query the inventory_item_location table for whatever sector you're looking for. 因此,您只需要查询stock_item_location表以查找所需的任何部门。 And you know what items are in that locaiton. 而且您知道那个地方有什么物品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM