mysql data type conversion

One, the problem

There is a table as shown in the figure below, we need to find out the data whose result value is greater than the reference_high value

Then we wrote the following SQL query

SELECT i.result,i.reference_high FROM report_item i
LEFT JOIN report r ON r.id=i.report_id 
WHERE r.org_id=54 AND r.report_status=1
AND r.add_date BETWEEN '2020-12-01' AND '2020-12-28' 
AND i.reference_high<>'' AND i.result<>''
AND i.result > i.reference_high ;

Then execute to view the results

The query result is not as we expected, there is a large amount of data that does not satisfy the query condition i.result> i.reference_high

 

2. Positioning

Looking at the SQL statement to build the table, we found that result and reference_high are varchar types, not numeric types, so the query results do not match expectations

 

Three, solve

Method 1: Modify the table field data type to numeric

But considering business usage scenarios, both fields may have non-numeric input, so it is not feasible

 

Method 2: Modify the query statement to convert the data type to numeric

Take the above data example

1. Implicit conversion: add 0 to the string to be compared before comparing, the data is successfully filtered

2. Display conversion

(1) Use the convert function: convert the string to a floating point number, and then compare, the data is successfully filtered

(2) Use the cast function: almost the same as the convert function

Guess you like

Origin blog.csdn.net/kk_gods/article/details/111839564