Compare Columns Where One is Similar to Part of Another

后端 未结 7 1366
再見小時候
再見小時候 2020-12-05 07:35

I\'m trying to write a Select statement where I can see if one column is like part of another.

tblNames 
ID    FullName                   FirstName
1     Mr.         


        
相关标签:
7条回答
  • 2020-12-05 07:43

    Try this:

    SELECT * FROM tblNames
    WHERE  ISNULL( CHARINDEX (FirstName , FullName),0) = 0
    

    The CHARINDEX will be faster (more performant) than a LIKE clause, as it doesn't have to take wildcards into account. The sample data above with small numbers of rows won't show a performance benefit, but when in the millions of rows, CHARINDEX would perform better.

    0 讨论(0)
  • 2020-12-05 07:43

    It looks OK, except you probably want to switch the order around in your where:

    WHERE Fullname not like '%' + FirstName + '%'
    
    0 讨论(0)
  • 2020-12-05 07:54

    Parentheses also would have fixed the issue.

    SELECT ID, FullName, FirstName
    FROM tblNames
    WHERE ('%' + FirstName + '%') not like Fullname
    
    0 讨论(0)
  • 2020-12-05 07:59

    Reverse the where, to something like this:

    Fullname not like '%' + FirstName + '%' 
    
    0 讨论(0)
  • 2020-12-05 08:05

    This worked for me:

    SELECT *
    FROM `table`
    WHERE `col1` NOT LIKE CONCAT('%', `col2`, '%')
    

    Found it here: http://www.edmondscommerce.co.uk/mysql/compare-two-columns-in-mysql/

    Somehow it only worked correctly with the concat-function (?).

    0 讨论(0)
  • 2020-12-05 08:08

    Switch the arguments to LIKE in the WHERE clause:

    SELECT ID, FullName, FirstName
    FROM tblNames
    WHERE Fullname not like '%' + FirstName + '%'
    

    The wildcard must be the second argument.

    0 讨论(0)
提交回复
热议问题