好的,这样我的代码可以正常工作,但是我确切希望得到的是首先显示post_featured ='Yes'并且不超过10天的结果?

如果有任何post_featured具有值是,它将保留在顶部,但前提是它不早于10天,我尝试过排序,但是以某种方式无法正常工作

我的密码

$search_fields = array('post_area','post_category','post_type');
$and_clause = array();
$params = array();

foreach($search_fields as $field){
    if(isset($_GET[$field]) && $_GET[$field] != 'All'){
        $and_clause[] = "`$field` = :$field";
        $params[] = array(":$field",$_GET[$field],PDO::PARAM_STR);
    }
}

$where_clause = '';
if(!empty($and_clause)){
    $where_clause = "WHERE " . implode(' AND ', $and_clause);
}

$query = "SELECT COUNT(*) FROM posts $where_clause";

if(empty($params)){
    $stmt = $db->query($query);
}else{
    $stmt = $db->prepare($query);
    foreach($params as $param)    {
        $stmt->bindValue($param[0],$param[1],$param[2]);
    }
    $stmt->execute();
}

$total = $stmt->fetchColumn();
$pages = ceil($total / $per_page);

$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default'   => 1,
'min_range' => 1,
),
)));

$offset = ($page - 1)  * $per_page;

$params[] = array(':per_page',$per_page, PDO::PARAM_INT);
$params[] = array(':offset',$offset, PDO::PARAM_INT);

$query = "SELECT * FROM posts $where_clause ORDER BY postID DESC LIMIT :per_page OFFSET :offset";

if(empty($params)){
    $stmt = $db->query($query);
}else{
    $stmt = $db->prepare($query);
    foreach($params as $param){
        $stmt->bindValue($param[0],$param[1],$param[2]);
    }
    $stmt->execute();
}
$result = $stmt->fetchAll();

最佳答案

给定表t

+------+---------------+------------+
| id   | post_featured | dte        |
+------+---------------+------------+
|    1 | yes           | 2016-07-15 |
|    2 | no            | 2016-07-15 |
|    3 | yes           | 2016-07-14 |
|    4 | yes           | 2016-06-15 |
|    5 | no            | 2016-06-15 |
|    1 | yes           | 2016-06-14 |
+------+---------------+------------+


并要求以两种方式进行排序

select t.*,
        case when t.post_featured = 'yes' and dte >= date_add(curdate() ,interval -10 day) then 1
        else 2
        end as srce
 from t
 order  by srce asc,id desc;


结果

+------+---------------+------------+------+
| id   | post_featured | dte        | srce |
+------+---------------+------------+------+
|    3 | yes           | 2016-07-14 |    1 |
|    1 | yes           | 2016-07-15 |    1 |
|    5 | no            | 2016-06-15 |    2 |
|    4 | yes           | 2016-06-15 |    2 |
|    2 | no            | 2016-07-15 |    2 |
|    1 | yes           | 2016-06-14 |    2 |
+------+---------------+------------+------+

10-04 15:15