mybatis-flex / mybatis-flex

mybatis-flex is an elegant Mybatis Enhancement Framework

Home Page:https://mybatis-flex.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

如何对union之后的数据排序

8OOOOOOOOD opened this issue · comments

QueryWrapper.create()
.select("s.id",
"COUNT(s.status=0 or NULL) as unread_msg_count",
"u.nick_name as sender",
"u.avatar"
)
.from(
QueryWrapper.create().from(MSG)
.select(MSG.ID, MSG.SENDER_ID.as("sid"), MSG.CONTENT, MSG.STATUS, MSG.TYPE,
MSG.CREATE_TIME)
.where(MSG.RECEIVER_ID.eq(userId).and(MSG.STATUS.eq(status, status != null)))
.union(QueryWrapper.create().from(MSG)
.select(MSG.ID, MSG.RECEIVER_ID.as("sid"), MSG.CONTENT, QueryMethods.column("1 as status"), MSG.TYPE,
MSG.CREATE_TIME)
.where(MSG.SENDER_ID.eq(userId)).and(MSG.STATUS.eq(status, status != null)))
// .orderBy(MSG.CREATE_TIME) 不行, 会加到第一个select中
).as("s")
.leftJoin(USER).as("u").on(USER.ID.eq(QueryMethods.column("sid")))
.groupBy("sid")
.orderBy("last_msg_time")

解决了, 嵌套一下就行:
.from(QueryWrapper.create().from(QueryWrapper.create().from(MSG)
.select(MSG.ID, MSG.SENDER_ID.as("sid"), MSG.CONTENT, MSG.STATUS, MSG.TYPE,
MSG.CREATE_TIME)
.where(MSG.RECEIVER_ID.eq(userId).and(MSG.STATUS.eq(status, status != null)))
.union(QueryWrapper.create().from(MSG)
.select(MSG.ID, MSG.RECEIVER_ID.as("sid"), MSG.CONTENT,
QueryMethods.column("1 as status"), MSG.TYPE,
MSG.CREATE_TIME)
.where(MSG.SENDER_ID.eq(userId)).and(MSG.STATUS.eq(status, status != null)))).as("a")
.orderBy("a.type asc", "a.create_time desc")
)