복붙노트

[SQL] 필드 단어가 포함 된 SQL SELECT

SQL

필드 단어가 포함 된 SQL SELECT

나는이 같은 결과를 반환 선택할 필요가 :

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

그리고 나는이 'word2 word3 단어 1'또는 세 가지의 '단어 1 word3 word2'또는 다른 조합으로 문자열을 포함 즉, 모든 결과가 필요합니다.

모든 단어는 결과에 있어야합니다.

해결법

  1. ==============================

    1.오히려 천천히,하지만 방법을 작업하는 단어 중 하나를 포함합니다 :

    오히려 천천히,하지만 방법을 작업하는 단어 중 하나를 포함합니다 :

    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%'
    

    당신이 빨리 뭔가를 원한다면, 당신은 전체 텍스트 검색에보고해야하고,이 각 데이터베이스 유형에 대한 매우 구체적이다.

  2. ==============================

    2.당신이 문자열이 다른 문자열의 부분 문자열인지 확인 LIKE를 사용하는 경우, 당신은 검색 문자열에서 패턴 일치 문자를 이스케이프해야합니다.

    당신이 문자열이 다른 문자열의 부분 문자열인지 확인 LIKE를 사용하는 경우, 당신은 검색 문자열에서 패턴 일치 문자를 이스케이프해야합니다.

    당신의 SQL 언어는 CHARINDEX를 지원하는 경우, 대신 그것을 사용하는 많은 쉽게 :

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

    또한, 허용 대답이와 방법은 단어 매칭보다는 일치하는 하위 문자열을 포함 것을 명심하시기 바랍니다. 따라서, 예를 들어, 문자열 'word1word2word3'은 여전히 ​​일치합니다.

  3. ==============================

    3.

     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
    
  4. ==============================

    4.대신 열 1이 '단어 1 word2 word3'CONTAINS을 MyTable SELECT * FROM의, 같은 그 단어 사이에 추가의 :

    대신 열 1이 '단어 1 word2 word3'CONTAINS을 MyTable SELECT * FROM의, 같은 그 단어 사이에 추가의 :

    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"'
    

    추신. 먼저 키워드가 포함되어 사용하기 전에 테이블에 전체 텍스트 검색을 활성화해야합니다. 자세한 내용은 여기 https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search보기

  5. ==============================

    5.

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

    변경 또는과 질문에 대한 편집을 기반으로.

  6. ==============================

    6.오라클 데이터베이스를 사용하는 경우에 당신은 사용하여이 쿼리를 포함 달성 할 수있다. 빠른 쿼리와 같은보다 querys 있습니다 포함되어 있습니다.

    오라클 데이터베이스를 사용하는 경우에 당신은 사용하여이 쿼리를 포함 달성 할 수있다. 빠른 쿼리와 같은보다 querys 있습니다 포함되어 있습니다.

    당신은 모든 단어가 필요한 경우

    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
    

    당신의 열의 타입 문맥을 필요로 인덱스를 포함합니다.

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

    7.당신은 일치하는 항목을 찾으려면.

    당신은 일치하는 항목을 찾으려면.

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

    SQL 서버 :

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

    정확히 일치를 얻으려면. 예 ( '; a 및 AB, AC,', ', B는' ') 일치하지 않습니다.

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

    8.MS SQL Server의 전체 텍스트 인덱스에서 "tesarus 검색"을 사용하려고합니다. 이것은 훨씬 더 당신이 기록의 수백만이있는 경우 검색에 "%"를 사용하는 것보다. tesarus는 다른 사람보다 메모리 소비의 작은 금액을 가지고있다. 이 기능을 검색하려고 :)

    MS SQL Server의 전체 텍스트 인덱스에서 "tesarus 검색"을 사용하려고합니다. 이것은 훨씬 더 당신이 기록의 수백만이있는 경우 검색에 "%"를 사용하는 것보다. tesarus는 다른 사람보다 메모리 소비의 작은 금액을 가지고있다. 이 기능을 검색하려고 :)

  9. ==============================

    9.가장 좋은 방법은 테이블의 열에서 전체 텍스트 인덱스를하고있다 사용은 LIKE 대신 포함

    가장 좋은 방법은 테이블의 열에서 전체 텍스트 인덱스를하고있다 사용은 LIKE 대신 포함

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

    10.왜 대신에 "의"사용하지?

    왜 대신에 "의"사용하지?

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

    11.이다 사용하여 질문에서 언급 한 것을 성취하는 가장 쉬운 방법 중 하나는 '~'NEAR 또는 함께 포함 함. 예를 들어, 다음 쿼리는 우리에게 특별히 단어 1, word2 및 word3을 포함하는 모든 열을 줄 것입니다.

    이다 사용하여 질문에서 언급 한 것을 성취하는 가장 쉬운 방법 중 하나는 '~'NEAR 또는 함께 포함 함. 예를 들어, 다음 쿼리는 우리에게 특별히 단어 1, word2 및 word3을 포함하는 모든 열을 줄 것입니다.

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

    또한 CONTAINSTABLE은 "단어 1", "word2"와 "word3"의 근접 정도에 따라 각 문서의 순위를 반환합니다. 문서는 문장이 포함 된 경우 예를 들어,는 "단어 1가 word2 및 word3이다,"그 용어가 가까이 서로 다른 문서에 비해 때문에 높은 것 순위.

    내가 추가하고 싶은 한 가지 다른 점은 우리는 또한 단어가 열 문구 내부 그들 사이의 특정 거리 안에있는 열을 찾을 근접어를 사용할 수 있다는 것입니다.

  12. ==============================

    12.사용하는 경우이 이상적으로 SQL Server 전체 텍스트 검색의 도움으로 수행해야합니다. 당신이 어떤 이유로 당신의 DB에서 해당 작업을 얻을 수없는 경우, 여기에 성능 집약적 인 솔루션입니다 : -

    사용하는 경우이 이상적으로 SQL Server 전체 텍스트 검색의 도움으로 수행해야합니다. 당신이 어떤 이유로 당신의 DB에서 해당 작업을 얻을 수없는 경우, 여기에 성능 집약적 인 솔루션입니다 : -

    -- 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
    
    
  13. ==============================

    13.

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

    이 컬럼 1이 부분 값이 단어가 포함되어 있습니다 모든 레코드를 표시합니다.

  14. ==============================

    14.

    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
    
  15. ==============================

    15.

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

    또는

    select * from table where name in ('word1','word2','word3')
    
  16. from https://stackoverflow.com/questions/14290857/sql-select-where-field-contains-words by cc-by-sa and MIT license