2014-10-07 152 views
-1

我有一個查詢返回接近1000條記錄。使用分頁,我每頁顯示100條記錄。很好...沒問題。我也可以按降序升序排列姓氏或名字。好吧到目前爲止。第一頁返回姓氏從A開始到C的記錄。我遇到的問題是,當我單擊姓氏下降時,我得到的姓氏以Z開頭的記錄。我查詢結束時的記錄,我想得到的結果會從C到A(什麼是顯示我的第一頁上...重複在每一頁相同的功能。PHP MySQL排序順序ASC/DESC只顯示記錄

這裏是我...

$orderColumn  =  'lastName'; 
$orderDirection  =  'ASC'; 

if(isset($_POST["oc"]) && $_POST["oc"] !== '') { $orderColumn  = $_POST["oc"]; } 
if(isset($_POST["od"]) && $_POST["od"] !== '') { $orderDirection  = $_POST["od"]; } 

$per_page = 100; 

$query = "SELECT * FROM table as t 
      LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID 
      LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID 
      WHERE t3.fk_utID = 7 and t.interviewed = 0"; 

$result = $db->query($query); 
$count =  mysql_num_rows($result); 

$total = ceil($count/$per_page); 

if ($_GET['page']) { 

    $page = $_GET['page']; 

} 


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

$query2 = "SELECT firstName as first, lastName as last FROM table 
       LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID 
       LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID 
       WHERE t3.fk_utID = 7 and interviewed = 0 order by $orderColumn $orderDirection LIMIT $offset, $per_page"; 

$res = $db-> query($query2); 

while($row = mysql_fetch_array($res)){ 

echo "<span style='display: inline-block; width: 15%;'>$row[first]</span>"; 
echo "<span style='display: inline-block; width: 15%;'>$row[last]</span>"; 

} 
+0

請確保你是在放置desc之前限制查詢! Aka通過推杆查詢使限制成爲子查詢和順序 – 2014-10-07 01:52:55

回答

0

要我是什麼在評論中說.. BTW我在我的手機,所以這可能是未格式化,或需要一段時間...

Select what_you_need 
From 
( select your_inner_select 
    From table t 
    LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID 
    LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID 
    WHERE t3.fk_utID = 7 and interviewed = 0 LIMIT $offset, $per_page 
    ORDER BY $orderColumn ASC 
)t 
order by $orderColumn $orderDirection 
+0

要使結果集確定,在「LIMIT」子句之前的內聯視圖「t」中應該有一個「ORDER BY」子句。 ORDER BY子句總是ASC,不會被切換。 – spencer7593 2014-10-07 03:55:43