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. 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 を使用する場合、2 つのクエリ結果に括弧を追加しないとエラーが報告され、「エイリアス」を追加せずに最初と 2 番目のサブクエリを追加するとエラーが報告されます。

1248 - Every derived table must have its own alias

まず、両方のサブクエリに 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

最初の追加、2 番目のサブクエリでは「エイリアス」が追加されず、結果は正常にクエリされますが、並べ替えに問題があります。

ここに画像の説明を挿入
解決策:
サブクエリに追加すると、limitキーワードが有効になります。

おすすめ

転載: blog.csdn.net/qq_44798321/article/details/126275664