Solution to MySQL sorting failure problem in MybatisPlus

As a CRUD engineer, when I was writing sql today, there was a problem. When sorting according to a decimal field, it was not sorted according to the requirements. At first, I mistakenly thought it was a mysql problem. I thought it was not sorted according to the floating point type. The operation is as fierce as a tiger, and the data is converted:
sql is as follows:

	select a_stk_pct_chg1 from land_hk_north_stat  order by 'a_stk_pct_chg1' desc 

misconception

Misunderstanding that this field is of type varchar. It cannot be sorted directly.
The solution
is to change the SQL without modifying the original design. We need to convert the string to a number first.

1. Operate the varchar type + 0, similar to the forced conversion of java

order by (a_stk_pct_chg1+0) desc

2. Use the function CAST (value as type) or CONVERT (value, type)

type can be DECIMAL (floating point), SIGNED (integer), UNSIGNED (unsigned integer)

order by CAST(a_stk_pct_chg1 as DECIMAL) desc

or

order by CONVERT(a_stk_pct_chg1,DECIMAL) desc

but! ! ! I have used all the above methods once, but it is really useless. I feel a chill in my heart. This is Barbie Q, but as a qualified programmer, I must not abandon it. After I checked the data carefully, I found clues in the sql log. , it turned out to be a problem with the escaping of the MybatisPlus variable definition!

Let's first go to some sql in xml

	<if test="params.sortFild != null ">
			ORDER BY  ${params.sortFild} DESC
		</if>

1. For a variable in the form of #{sortFild}, Mybatis will treat it as a string value. After the variable is replaced successfully, quotes will be added to the variable value by default.
The result is

ORDER BY ‘sortFild' DESC

2. For a variable in the form of ${sortFild}, Mybatis will treat it as a direct variable, that is, after the variable is successfully replaced, it will not be quoted again.

 ORDER BY  sortFild  DESC

Then run the service, the problem is perfectly solved~

​Follow
my WeChat public
accountinsert image description here

Guess you like

Origin blog.csdn.net/CharlesYooSky/article/details/126138610