简体   繁体   中英

How to select true value when combining alphanumeric?

mysql: customer_number = int (cannot be changed)

$query = "SELECT * FROM clients WHERE customer_number= '123F'" 

The RESULT should be empty.

The query has a result which is incorrect because, MySQL ignore any alphabet character which form part of the value with an integer datatype, eg.'F'

You can check if the value provided is strictly integer.

$query = "SELECT * FROM clients WHERE customer_number= '123F' 
AND '123F' REGEXP '^-?[0-9]+$'";

AND needs both conditions compulsorily.

So, even if MySQL ignores F from 123F and treats it as 123 , second condition will return FALSE and 123F will fail regular expression of strictly integer condition.

This will have following results:

123 -> pass

123F -> fail

You can cast customer_number to string:

SELECT *
FROM clients
WHERE CAST(customer_number as CHAR(50)) = '123F'

The above query is of course not SARGable. Consider processing the comparison argument on the client side before the construction of the query.

Demo here

Or check as first condition if the integer from the string equal the string (change the string to your fieldname) :

SELECT * FROM clients 
WHERE
  '123F'+0 = '123F' 
AND
  customer_number= '123F';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM