在SQL中从数组中的特定值查找数据
早上好 我的记录中有一个Allowed systems字段,可以包含一个数组,例如:22、18、21 我想做的是,如果system 18正在访问数据库,并且正在提取system 18允许的所有记录,那么我如何用sql编写这些记录在SQL中从数组中的特定值查找数据,sql,sql-server,Sql,Sql Server,早上好 我的记录中有一个Allowed systems字段,可以包含一个数组,例如:22、18、21 我想做的是,如果system 18正在访问数据库,并且正在提取system 18允许的所有记录,那么我如何用sql编写这些记录 +----------+----------------+------------+ | AdvertID | AllowedSystems | AdvertName | +----------+----------------+------------+ | 47
+----------+----------------+------------+
| AdvertID | AllowedSystems | AdvertName |
+----------+----------------+------------+
| 47 | 22, 18, 21, 3 | GeorgesAd |
+----------+----------------+------------+
| 49 | 2, 7, 9, 6 | StevesAd |
+----------+----------------+------------+
| 47 | 18, 12, 32, 8 | PetesAd |
+----------+----------------+------------+
如蒙协助,将不胜感激
祝你今天愉快
Paul Jacobs注意:我在搜索列的开头添加了一个空格,在末尾添加了一个逗号,以说明18是列表中的第一个或最后一个条目的情况。然后在字符串中搜索“18”
select *
from YourTable
where charindex(' 18,', ' ' + AllowedSystems + ',') <> 0
选择*
从你的桌子上
其中charindex('18',''允许系统+',')0
注意:我在搜索列的开头加了一个空格,在末尾加了一个逗号,以说明18是列表中的第一个或最后一个条目的情况。然后在字符串中搜索“18”
select *
from YourTable
where charindex(' 18,', ' ' + AllowedSystems + ',') <> 0
选择*
从你的桌子上
其中charindex('18',''允许系统+',')0
这将首先测试性能最佳的情况,希望从由于非规范化结构而注定效率低下的查询中获得一些性能
前两个WHERE
子句可以利用AllowedSystems
上的索引,尽管这可能仅在少数情况下有用,具体取决于您的数据
select AdvertID, AdvertName
from MyTable
where AllowedSystems = '18'
or AllowedSystems like '18,%'
or AllowedSystems like '%, 18'
or AllowedSystems like '%, 18,%'
这将首先测试性能最好的情况,希望从由于非规范化结构而注定是低效的查询中获得一些性能 前两个
WHERE
子句可以利用AllowedSystems
上的索引,尽管这可能仅在少数情况下有用,具体取决于您的数据
select AdvertID, AdvertName
from MyTable
where AllowedSystems = '18'
or AllowedSystems like '18,%'
or AllowedSystems like '%, 18'
or AllowedSystems like '%, 18,%'
首先,这对于数据结构来说是个坏主意。您可能应该通过添加一个
AllowedSystems
表来进行规范化,该表为每对系统和广告添加一条记录
其次,您可能希望使用以下方法:
SELECT AdvertID, AdvertName
FROM MyTable
WHERE AllowedSystems LIKE '%18%'
当你有超过100个系统时,你会遇到问题,因为没有办法判断命中的是18
还是118
还是181
编辑:
或者您可以使用RedFilter的multiple
WHERE
条件来避免上述18
、118
或181
问题。首先,这对于数据结构来说是个坏主意。您可能应该通过添加一个AllowedSystems
表来进行规范化,该表为每对系统和广告添加一条记录
其次,您可能希望使用以下方法:
SELECT AdvertID, AdvertName
FROM MyTable
WHERE AllowedSystems LIKE '%18%'
当你有超过100个系统时,你会遇到问题,因为没有办法判断命中的是18
还是118
还是181
编辑:
或者您可以使用RedFilter的多个
WHERE
条件来避免上述18
、118
、或181
,性能不佳的方式是:
SELECT AdvertID, AdvertName
FROM YourTable
WHERE ', ' + AllowSystems + ', ' LIKE '%, 18, %'
但是,理想情况下,您应该有一个具有复合键的额外表:
Table: AdvertAllowedSystem
AdvertID
SystemID
因此,您可以执行更高性能的可搜索查询:
SELECT a.AdvertID, a.AdvertName
FROM AdvertAllowedSystem s
INNER JOIN Advert a ON s.AdvertId = a.AdvertId
WHERE s.SystemId = 18
表现不佳的方式是:
SELECT AdvertID, AdvertName
FROM YourTable
WHERE ', ' + AllowSystems + ', ' LIKE '%, 18, %'
但是,理想情况下,您应该有一个具有复合键的额外表:
Table: AdvertAllowedSystem
AdvertID
SystemID
因此,您可以执行更高性能的可搜索查询:
SELECT a.AdvertID, a.AdvertName
FROM AdvertAllowedSystem s
INNER JOIN Advert a ON s.AdvertId = a.AdvertId
WHERE s.SystemId = 18
此外,如果您有可能更改“创建物化视图”的设计,则可以使用或排列并取消排列此外,如果您有可能更改“创建物化视图”的设计,则可以使用或排列并取消排列