SQL SELECT WHERE字段包含单词


561

我需要一个选择将返回如下结果:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'

我需要所有结果,即这包括带有'word2 word3 word1'或'word1 word3 word2'或三者的任何其他组合的字符串。

所有单词都必须包含在结果中。

Answers:


842

相当慢,但是可以包括任何单词的工作方法:

SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
   OR column1 LIKE '%word2%'
   OR column1 LIKE '%word3%'

如果您需要所有单词,请使用以下命令:

SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
  AND column1 LIKE '%word2%'
  AND column1 LIKE '%word3%'

如果需要更快的速度,则需要研究全文搜索,这对于每种数据库类型都是非常特定的。


3
+ 1我同意它的速度较慢,但​​可以通过良好的索引处理来缓解
Preet Sangha 2013年

12
当您搜索以通配符开头的LIKE时,@ PreetSangha Indexing?请告诉我如何!
Popnoodles

1
在PostgreSQL 9.1和更高版本中,您可以创建三元组索引,该索引可以为此类搜索建立索引。
mvp 2014年

2
@AquaAlex:如果文本包含,则您的声明将失败word3 word2 word1
mvp

3
这种方法的另一个缺点:'%word%'还会找到'words','crosswordpuzzle'和'sword'(仅作为示例)。我必须做一个column1 LIKE'word'或column1 LIKE'word%'或column1 LIKE'%word'或column1 LIKE'word'才能找到完全匹配的单词-对于不包含单词的条目,它仍然会失败只是用空格隔开。
BlaM

81

请注意,如果LIKE用于确定一个字符串是否是另一个字符串的子字符串,则必须对搜索字符串中的模式匹配字符进行转义。

如果您的SQL语言支持CHARINDEX,使用它会容易得多:

SELECT * FROM MyTable
WHERE CHARINDEX('word1', Column1) > 0
  AND CHARINDEX('word2', Column1) > 0
  AND CHARINDEX('word3', Column1) > 0

另外,请记住,此方法和接受的答案中的方法仅覆盖子字符串匹配,而不是单词匹配。因此,例如,字符串'word1word2word3'仍将匹配。


1
如果您的搜索词是一个变量,而不是必须在搜索之前添加'%'字符,这似乎容易得多
ShaneBlake

4
在Microsoft SQL服务器和引擎中,我们应该InStr()改用CHARINDEX
23W

6
@ 23W MS SQL中没有InStr
RomanoZumbé17

19

功能

 CREATE FUNCTION [dbo].[fnSplit] ( @sep CHAR(1), @str VARCHAR(512) )
 RETURNS TABLE AS
 RETURN (
           WITH Pieces(pn, start, stop) AS (
           SELECT 1, 1, CHARINDEX(@sep, @str)
           UNION ALL
           SELECT pn + 1, stop + 1, CHARINDEX(@sep, @str, stop + 1)
           FROM Pieces
           WHERE stop > 0
      )

      SELECT
           pn AS Id,
           SUBSTRING(@str, start, CASE WHEN stop > 0 THEN stop - start ELSE 512 END) AS Data
      FROM
           Pieces
 )

询问

 DECLARE @FilterTable TABLE (Data VARCHAR(512))

 INSERT INTO @FilterTable (Data)
 SELECT DISTINCT S.Data
 FROM fnSplit(' ', 'word1 word2 word3') S -- Contains words

 SELECT DISTINCT
      T.*
 FROM
      MyTable T
      INNER JOIN @FilterTable F1 ON T.Column1 LIKE '%' + F1.Data + '%'
      LEFT JOIN @FilterTable F2 ON T.Column1 NOT LIKE '%' + F2.Data + '%'
 WHERE
      F2.Data IS NULL

2
好极了!主席先生,如何开始学习这一功能?什么是碎片?你能告诉我关于这行的伪代码吗?SUBSTRING(@str,开始,在停止> 0时停止,然后开始-以ELSE 512 END开始时
为例

2
此举令人难以置信,我真的很嫉妒:( ______________________________________________________________________________________ + F2.Data +'%'
艾哈迈德·阿尔卡拉基

13

代替SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3',在这些词之间添加And:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 And word2 And word3'

有关详细信息,请参见此处 https://msdn.microsoft.com/en-us/library/ms187787.aspx

更新

要选择短语,请使用双引号,例如:

SELECT * FROM MyTable WHERE Column1 CONTAINS '"Phrase one" And word2 And "Phrase Two"'

ps您必须先在表上启用全文搜索,然后才能使用contains关键字。有关更多详细信息,请参见此处 https://docs.microsoft.com/zh-cn/sql/relational-databases/search/get-started-with-full-text-search


8
SELECT * FROM MyTable WHERE 
Column1 LIKE '%word1%'
AND Column1 LIKE '%word2%'
AND Column1 LIKE  '%word3%'

根据对问题的更改已更改ORAND


我需要将所有单词以任意组合形式包含在结果中
Mario M

4

如果使用的是Oracle数据库,则可以使用包含查询来实现。包含查询比类似查询更快。

如果你需要所有的话

SELECT * FROM MyTable WHERE CONTAINS(Column1,'word1 and word2 and word3', 1) > 0

如果您需要任何话

SELECT * FROM MyTable WHERE CONTAINS(Column1,'word1 or word2 or word3', 1) > 0

列上包含CONTEXT类型的需求索引。

CREATE INDEX SEARCH_IDX ON MyTable(Column) INDEXTYPE IS CTXSYS.CONTEXT

1
@downvoters感谢您告诉我们答案有什么问题。相同的查询每天在我们的企业解决方案中运行超过1000次,没有任何问题:)
mirmdasif

2
OP没有指定正在使用哪个数据库,并且每个人都假设这是Sql Server。但是,由于您在响应中指定了Oracle,所以我不理解拒绝投票的人。
EAmez

4

如果您只想找到一个匹配项。

SELECT * FROM MyTable WHERE INSTR('word1 word2 word3',Column1)<>0

SQL Server:

CHARINDEX(Column1, 'word1 word2 word3', 1)<>0

获得完全匹配。示例(';a;ab;ac;',';b;')将不匹配。

SELECT * FROM MyTable WHERE INSTR(';word1;word2;word3;',';'||Column1||';')<>0

1
'INSTR'不是公认的内置函数名称。在我的SQL Server中。
Durgesh Pandey

0

尝试在MS SQL Server的全文本索引中使用“ tesarus搜索”。如果您有数百万条记录,这比在搜索中使用“%”更好。tesarus的内存消耗比其他小。尝试搜索此功能:)


0

最好的方法是在表中的列上建立全文索引,并使用Contain代替LIKE

SELECT * FROM MyTable WHERE 
contains(Column1 , N'word1' )
AND contains(Column1 , N'word2' )
AND contains(Column1 , N'word3' )

0

为什么不使用“ in”代替?

Select *
from table
where columnname in (word1, word2, word3)

2
因为它不起作用。您是否真的尝试过?
mvp

2
我相信这只会返回完全匹配。
默里

1
我也误解了最初的问题:他们不想找到完全匹配的词,而是一个单词是(可能是)较大字符串的一部分。对于更简单的“精确匹配”情况,如果单词在单引号之间(参见SQLfiddle),则可以使用此方法
sc28

0

实现问题中最简单的方法之一是将CONTAINS与NEAR或'〜'一起使用。例如,以下查询将为我们提供所有包含word1,word2和word3的列。

SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 NEAR word2 NEAR word3')

SELECT * FROM MyTable WHERE CONTAINS(Column1, 'word1 ~ word2 ~ word3')

另外,CONTAINSTABLE基于“ word1”,“ word2”和“ word3”的接近程度返回每个文档的等级。例如,如果一个文档包含句子“单词1是单词2和单词3”,则其排名会很高,因为这些术语比其他文档更接近彼此。

我想补充的另一件事是,我们还可以使用接近性项查找单词在列词组内单词之间的特定距离内的列。


0

理想情况下,如果使用此工具,应在sql server全文搜索的帮助下完成。但是,如果由于某种原因而无法在数据库上正常工作,则可以使用以下性能密集型解决方案:

-- table to search in
CREATE TABLE dbo.myTable
    (
    myTableId int NOT NULL IDENTITY (1, 1),
    code varchar(200) NOT NULL, 
    description varchar(200) NOT NULL -- this column contains the values we are going to search in 
    )  ON [PRIMARY]
GO

-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
  id nvarchar(1000)
)
AS
BEGIN
  DECLARE @String nvarchar(100);

  WHILE LEN(@StringInput) > 0
  BEGIN
    SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
    LEN(@StringInput)));
    SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
    (
    @Delimiter, @StringInput
    ),
    0
    ), LEN
    (
    @StringInput)
    )
    + 1, LEN(@StringInput));

    INSERT INTO @OutputTable (id)
      VALUES (@String);
  END;

  RETURN;
END;
GO

-- this is the search script which can be optionally converted to a stored procedure /function


declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain

if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
 select 1 as Priority ,myTableid, code, Description from myTable order by Description 
 return;
end

declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)

insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')

insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
--  id
-------------
-- infection
-- upper
-- acute
-- genito

delete s from @splitTable s join @nonWordTable n  on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable);  -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);

with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search  -- exact matches have highest priority
union                                      
select myTableid, @highestPriority-1 as Priority from myTable where Description like  @search + '%'  -- then with something at the end
union                                      
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union                                      
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
                     -- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description)  from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
                                                                              -- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
 select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
                     -- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex 
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
                              -- their sequence in the field value is taken into account for higher priority
    select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
    from wordIndexRatings w left join 
    (
     select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
     from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
     group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
    ) 
    sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select  w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId =  w2.myTableId 
where w1.word <> w2.word group by w1.myTableid 
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority  from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable  on m.myTableId = myTable.myTableId 
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging

-2
SELECT * FROM MyTable WHERE Column1 Like "*word*"

这将显示column1包含部分值的所有记录word


-2
DECLARE @SearchStr nvarchar(100)
SET @SearchStr = ' '



CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL

        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END

SELECT ColumnName, ColumnValue FROM #Results

DROP TABLE #Results

2
感谢您提供此代码段,它可能会提供一些有限的即时帮助。通过说明为什么这是解决问题的好方法,适当的解释将大大提高其长期价值,对于其他类似问题的读者也将更有用。请编辑您的答案以添加一些解释,包括您所做的假设。
Mogsdad '18

-5
select * from table where name regexp '^word[1-3]$'

要么

select * from table where name in ('word1','word2','word3')

3
是“ regexp”标准SQL吗?
彼得·莫滕森

2
对于第二个查询,是否不应该使用单词?
彼得·莫滕森

1
此代码似乎检查该列是否等于三个单词之一。问题是关于检查该列是否包含 所有三个词。
2014年

7
嗨,这很可能解决了问题...但是,如果您可以编辑答案并提供一些有关其工作原理和原因的说明,那将是很好的方法:)不要忘记-堆栈溢出有很多新手,他们可以从您的专业知识中学到一两个东西-对您而言显而易见的可能对他们而言不是。
Taryn East 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.