pagehelper Mysql union遇上Order By的坑

需求

pagehelper分页查询: 表fu_plan 有字段follow_up_status ,该字段的值可以是1 或 2 。
条件如下
1、值为2的数据在最前面,值为1的值在后面
2、值为2的数据按字段start_time  ,create_time 都倒序排列
3、值为1的数据按字段start_time正序  ,create_time 倒序排列
思路

1、先分别按follow_up_status 的值查出对应的数据并排序。
2、合并两个子查询的结果
3、载根据合并的及结果 按follow_up_status 倒序排序

先上完整sql


SELECT * FROM 

			(SELECT fp.*  FROM 
					fu_plan fp JOIN hm_project_customer hp on  fp.archive_id = hp.health_archive_id 
					and hp.customer_status = 1
					
					
					WHERE
						fp.archive_id = 404
						and fp.follow_up_status = 1
						ORDER BY fp.start_time  desc,fp.create_time desc
						LIMIT 0,10
			 ) as t1
			 
			 UNION
			 
			 (SELECT fp.*  FROM 
					fu_plan fp JOIN hm_project_customer hp on  fp.archive_id = hp.health_archive_id 
					and hp.customer_status = 1
					
					WHERE
					
						fp.archive_id = 404
						and fp.follow_up_status = 2
						ORDER BY fp.start_time  asc,fp.create_time desc
						LIMIT 0,100
			 ) 
			 
			 ORDER BY follow_up_status desc;

坑1

使用 UNION 如果不将俩个查询结果分别添加括号时会报错,加了且第一,二个子查询都不加“别名” 时报错
1248 - Every derived table must have its own alias
第一,二个子查询都加了as xx ”别名“时报错
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as t2
			 
			 ORDER BY follow_up_status desc' at line 27

坑2

第一加,第二个子查询不加了 ”别名“时成功查询出结果,但是排序有问题

在这里插入图片描述
解决办法:
在子查询中加入,limit 关键字生效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐睡睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值