foreword
irrelevant to this article
"I'm in" ….
text
What are you going to talk about today?
In fact, it is very simple. When querying data, you want to sort and query data according to the custom order of the fields you specify.
A few points that will be covered in this article:
1. How to achieve sorting with pure sql
2. How to achieve custom sorting with pure sql
3. How to sort in combination with java
4. How to use the sorting sql in point 2 in combination with mybatis
The process of speaking may not be in order.
play
Look at the example table first:
product product table
Example data:
Sorting, order by asc or order by desc is very simple
for example:
SELECT * FROM product ORDER BY id DESC ;
So if there is a requirement that you can't sort by id, you need to sort by product name, how should you deal with it?
For example, specifying this fixed order:
First compare the conventional way:
① Add sort field order by sort
② Add a sequence configuration table association table query
These two methods, I'm sorry, are too conventional, so I won't talk about them in this article.
Our current requirements are a little stricter, and you are not allowed to touch the structure of the watch.
What to do?
Use ORDER BY FIELD
Example:
SELECT * FROM product ORDER BY FIELD(NAME,'biscuit','book','chess','ink','pen','paper');
In terms of sql, it is OK to do this for the time being.
So if what I said is that we are writing functional requirements now, using java springboot mybatis, how to solve the custom order?
① Find the data normally, then loop through the variables, and wash the data according to the product name.
Routine operation, no introduction.
② Through the mybatis that we usually use, that is, to pass parameters, and then execute SQL queries to achieve.
That is to execute this sql:
SELECT *
FROM product
ORDER BY FIELD(NAME,'biscuit','book','chess','ink','pen','paper');
Simply write, mapper:
/**
* @author JCccc
*/
@Mapper
public interface ProductMapper {
List<Product> queryProductList(@Param("nameSortList") List<String> regularNameSortList);
}
mapper.xml :
<!--查询-->
<select id="queryProductList" resultMap="BaseResultMap">
SELECT
ID,NAME,STATUS
FROM product
<if test="nameSortList != null and nameSortList.size >0 ">
ORDER BY FIELD
<foreach collection="nameSortList" item="name" open="(NAME," separator="," close=")">
#{name}
</foreach>
</if>
</select>
Call example:
The result is OK:
Pay attention to details:
Well, that's all for this article.