Difference between LIKE and = in MYSQL?

后端 未结 12 1884

What\'s the difference between

SELECT foo FROM bar WHERE foobar=\'$foo\'

AND

SELECT foo FROM bar WHERE foobar LIKE\'$foo\'         


        
相关标签:
12条回答
  • 2020-11-29 09:06

    I found an important difference between LIKE and equal sign = !

    Example: I have a table with a field "ID" (type: int(20) ) and a record that contains the value "123456789"

    If I do:

    SELECT ID FROM example WHERE ID = '123456789-100'
    

    Record with ID = '123456789' is found (is an incorrect result)

    If I do:

    SELECT ID FROM example WHERE ID LIKE '123456789-100'
    

    No record is found (this is correct)

    So, at least for INTEGER-fields it seems an important difference...

    0 讨论(0)
  • 2020-11-29 09:07

    With the example in your question there is no difference.

    But, like Jesse said you can do wildcard matching

    SELECT foo FROM bar WHERE foobar LIKE "Foo%"
    
    SELECT foo FROM bar WHERE foobar NOT LIKE "%Foo%"
    

    More info:

    http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

    0 讨论(0)
  • 2020-11-29 09:08

    In my case I find Like being faster than =

    • Like fetched a number of rows in 0.203 secs the first time then 0.140 secs

    • = returns fetched the same rows in 0.156 secs constantly

    Take your choice

    0 讨论(0)
  • 2020-11-29 09:11

    The end result will be the same, but the query engine uses different logic to get to the answer. Generally, LIKE queries burn more cycles than "=" queries. But when no wildcard character is supplied, I'm not certain how the optimizer may treat that.

    0 讨论(0)
  • 2020-11-29 09:17

    LIKE can do wildcard matching:

    SELECT foo FROM bar WHERE foobar LIKE "Foo%"
    

    If you don't need pattern matching, then use = instead of LIKE. It's faster and more secure. (You are using parameterized queries, right?)

    0 讨论(0)
  • 2020-11-29 09:17

    In your example, they are semantically equal and should return the same output.

    However, LIKE will give you the ability of pattern matching with wildcards.

    You should also note that = might give you a performance boost on some systems, so if you are for instance, searching for an exakt number, = would be the prefered method.

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