mysql同一个表,多种条件的多种排序,这里使用了php结合mysql实现
/**
* 这里是一个以Yii框架开发的一个程序,其他框架同理
*
* 示例使用场景介绍:
* 1、一个类似滴滴的APP订单列表
* 2、订单状态为 1, 2, 3, 4 的始终在其他状态的前面
* 3、订单状态为 1, 2, 3, 4 的按照订单生成时间倒序排
* 4、订单状态不为 1, 2, 3, 4 的始终在 1, 2, 3, 4 状态的后面
* 5、订单状态不为 1, 2, 3, 4 的按照订单生成时间倒序排
*/
public function actionDemo()
{
$page = 10;
$limit = 5;
$offset = ($page - 1) * $limit;
$where = 'order_status IN( 1, 2, 3, 4 )';
$whereNot = 'order_status NOT IN( 1, 2, 3, 4 )';
$Order = Order::find()->select(['order_id', 'order_status'])->where($where);
$totalCount = $Order->count();
if ($list = $Order->offset($offset)->limit($limit)->orderBy('order_id DESC')->asArray()->all()) {
if ( ( $count = $limit - count($list) ) != 0 ) {
$listNews = Order::find()->select(['order_id', 'order_status'])->where($whereNot)->offset(0)->limit($count)->orderBy('order_id DESC')->asArray()->all();
$list = array_merge($list, $listNews);
}
} else {
$offset -= $totalCount;
$list = Order::find()->select(['order_id', 'order_status'])->where($whereNot)->offset($offset)->limit($limit)->orderBy('order_id DESC')->asArray()->all();
}
$this->returnAsJson(200, '', $list);
}
例子二:
/**
* 活动列表
*
* 要求:进行中的在最前面,其次未开始、已结束
*
* @param int $page
* @return array
*/
public static function getList($page = 1)
{
$where = "activity_delflag = 1 AND activity_online = 1";
$limit = 10;
$offset = ($page - 1) * $limit;
$time = time();
// 进行中where
$whereConduct = $where . " AND {$time} > activity_start_time AND {$time} < activity_end_time";
// 未开始where
$whereNotBegin = $where . " AND {$time} < activity_start_time";
// 已结束where
$whereEnd = $where . " AND {$time} > activity_end_time";
$Activity = self::find();
$countConduct = $Activity->where($whereConduct)->count();
$countNotBegin = $Activity->where($whereNotBegin)->count();
$offsetNotBegin = $offset - $countConduct;
$offsetEnd = $offsetNotBegin - $countNotBegin;
if ($list = $Activity->where($whereConduct)->offset($offset)->limit($limit)->asArray()->all()) {
if (($count = $limit - count($list)) != 0) {
$listNews = $Activity->where($whereNotBegin)->offset(0)->limit($count)->asArray()->all();
$list = array_merge($list, $listNews);
if (($count = $limit - count($list)) != 0) {
$listNews = $Activity->where($whereEnd)->offset(0)->limit($count)->asArray()->all();
$list = array_merge($list, $listNews);
}
}
} else if ($list = $Activity->where($whereNotBegin)->offset($offsetNotBegin)->limit($limit)->asArray()->all()) {
if (($count = $limit - count($list)) != 0) {
$listNews = $Activity->where($whereEnd)->offset(0)->limit($count)->asArray()->all();
$list = array_merge($list, $listNews);
}
} else {
$list = $Activity->where($whereEnd)->offset($offsetEnd)->limit($limit)->asArray()->all();
}
return $list;
}