SORT排序
根据数据表sys_series中HOT(int类型)进行升序排列:
- 原来的数据库中存储:
- 排序
# 结果是HOT字段为null的所有数据都排在最前面,不为null的数据按升序排列
SELECT * FROM sys_series ORDER BY HOT;
# 结果是HOT字段为null的所有数据都排在最后面,不为null的数据按数据库中原本的先后顺序排列
SELECT * FROM sys_series ORDER BY isnull(HOT);
# 结果是HOT字段为null的所有数据都排在最后面,不为null的数据按升序排列
SELECT * FROM sys_series ORDER BY isnull(HOT), HOT;
# 结果是HOT字段为null的所有数据都排在最前面,不为null的数据按升序排列
SELECT * FROM sys_series ORDER BY HOT, isnull(HOT);
最后一种相当于第一种。因为对于ORDER BY排序的优先级是从前往后,先按第一个order by的字段进行排序,如果遇到了两个相同的,则按照第二个排列,eg:
# 先按NEED的值升序排列,若NEED值相等,则根据HOT的值升序
SELECT * FROM sys_series ORDER BY NEED, HOT;
# 先按NEED的值升序排列,若NEED值相等,则根据HOT的降序
SELECT * FROM sys_series ORDER BY NEED, HOT DESC;
Mybatis
List<SysSeries> getLike();
<select id="getLike" resultType="java.util.List">SELECT * FROM sys_series ORDER BY ISNULL(HOT), HOT
</select>
报错
The error occurred while handling results### SQL: SELECT * FROM sys_series ORDER BY ISNULL(HOT), HOT### Cause: java.lang.UnsupportedOperationException
原因
resultType配置错误,返回的结果为List,所以resultType应该配置为实体类的路径:resultType=“com.harmony.supreme.modular.series.entity.SysSeries”,eg:
List<String> getAllIds();
<select id="getAllIds" resultType="java.lang.String"></select>
SysSeries selectById(String id);
<select id="selectById" resultType="com.harmony.supreme.modular.series.entity.SysSeries"></select>
List<Map<String, Object>> countByIdList(@Param("idList") List<String> idList);
<select id="countByIdList" resultType="java.util.Map"></select>
问答
根据 int 类型的字段 SORT 进行升序排列,如果SORT值为null空,则按创建时间升序排列:
select * from table_name ORDER BY ISNULL(SORT), SORT,CREATE_TIME
select * from table_name where (create_user = 'xxx') ORDER BY ISNULL(SORT), SORT,CREATE_TIME
List<TableName> get(String createUser);
<select id="get" parameterType="java.lang.String" resultType="com.harmony.supreme.modular.entity.tableName ">SELECT * from table_name WHERE CREATE_USER = #{createUser} ORDER BY ISNULL(SORT), SORT, CREATE_TIME
</select>
把createUser等于eq的条件改为id属于in的条件:
List<tableName> getByLink(List<String> ids);
<select id="getByLink" parameterType="java.util.List" resultType="com.harmony.supreme.modular.entity.tableName ">SELECT *from table_tableWHERE ID IN<foreach collection="list" item="id" separator="," open="(" close=")">#{id}</foreach>ORDER BY ISNULL(SORT), SORT, CREATE_TIME
</select>