Strict matching of strings and integers

前端 未结 2 1488
醉梦人生
醉梦人生 2020-12-12 02:56

I am writing a flexible search mechanism for a customer\'s website. I am utilizing union clauses to query a number of different fields in the database in search of a string

相关标签:
2条回答
  • 2020-12-12 03:26

    How about replacing:

    SELECT * FROM test_table WHERE phone = 'email@example.com'
    

    with:

    SELECT * FROM test_table WHERE phone = 'email@example.com' and phone <> 0
    

    <> means different from.

    This will work for you because you are using 0 in the phone column to mean there isn't a phone number (although it would be better style to use NULL for no phone number).

    0 讨论(0)
  • 2020-12-12 03:35

    This query should fail:

    SELECT * FROM test_table WHERE cast(phone as char) = 'email@example.com';
    

    The cause of the original problem is that when comparing strings and numbers, it converts the string to a number (so you can write where phone = '123'). You need to use an explicit cast of the field to make it a string-to-string comparison, to prevent this default conversion.

    Unfortunately, casting like this is likely to prevent it from using indexes. Even if the field is already char, the cast apparently prevents it from indexing.

    You could also solve it during input validation: if phone is an integer, don't allow the user to provide a non-integer value in the search field.

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