2012-02-15 77 views
2

在下面的SQL語句中,結果按順序返回。如果他們按照升序或降序排列,這將是有道理的,但似乎這裏沒有秩序。ORDER BY問題沒有用子選擇正確排序

任何有關爲什麼ORDER BY函數未按'日期'別名排序的見解將非常感激。

SQL語句:

SELECT id, date, type 
    FROM (SELECT resume_id AS id, DATE_FORMAT(date_mod, '%M %e, %Y') AS date, 'resume' AS TYPE 
       FROM resumes 
       WHERE user_id = '$user_id' 
      UNION ALL 
      SELECT profile_id, DATE_FORMAT(date_mod, '%M %e, %Y') AS date, 'profile' 
       FROM profiles 
       WHERE user_id = '$user_id' 
      ORDER BY date DESC LIMIT 5) AS d1 
    ORDER BY date 

結果:

Resume was updated on February 14, 2012 
Resume was updated on February 15, 2012 
Resume was updated on February 15, 2012 
Resume was updated on February 9, 2012 
Profile was updated on February 9, 2012 
+3

它正確排序,因爲內部查詢正在返回日期STRING,而不是日期FIELD。 – 2012-02-15 20:58:51

+0

你有看起來像一個小錯誤,可能無關緊要,但仍值得指出。您在第一個內部查詢中選擇了「resume_id AS id」,但在第二個查詢中僅選擇了「profile_id」。這應該是'profile_id AS id'。在你的情況下,你沒有使用id,所以它沒關係,但如果你最終使用id,可能是一個令人討厭的bug。在第二個查詢中,您也只是選擇''profile''而不是''profile'AS type''。 (我在發佈的答案中做出了這些修復) – 2012-02-15 21:13:37

回答

4

它是對它們進行排序爲字符串,因爲你已經轉換日期使用DATE_FORMAT字符串(注意,作爲一個字符串「2月15日.. 。「低於」2月9日...「,因爲1在」字母表「中出現在9之前)。解決方案是按照date_mod中的實際日期排序。你可以直接通過剛剛在date_mod的選擇添加和更改訂單,這樣做:

SELECT id, date, date_mod, type 
FROM (
    SELECT resume_id AS id, 
    DATE_FORMAT(date_mod, '%M %e, %Y') AS date, 
    date_mod, 
    'resume' AS type 
    FROM resumes 
    WHERE user_id = '$user_id' 
    UNION ALL 
    SELECT profile_id AS id, 
    DATE_FORMAT(date_mod, '%M %e, %Y') AS date, 
    date_mod, 
    'profile' AS type 
    FROM profiles 
    WHERE user_id = '$user_id' 
    ORDER BY date_mod DESC 
    LIMIT 5 
) AS d1 
ORDER BY date_mod 

但更妙的是僅由date_mod在子查詢中選擇(即簡化它沒有格式版本),並做最後DATE_FORMAT在外部查詢:

SELECT id, DATE_FORMAT(date_mod, '%M %e, %Y') AS date, type 
FROM (
    SELECT resume_id AS id, date_mod, 'resume' AS type 
    FROM resumes 
    WHERE user_id = '$user_id' 
    UNION ALL 
    SELECT profile_id AS id, date_mod, 'profile' AS type 
    FROM profiles 
    WHERE user_id = '$user_id' 
    ORDER BY date_mod DESC 
    LIMIT 5 
) AS d1 
ORDER BY date_mod 
+0

感謝@Ben,這個概念非常有意義,它基於日期字符串進行排序,而不是date_mod字段。 – jsuissa 2012-02-15 21:17:00

1

它訂購你的格式化的日期字符串爲字符串,並想將它們順序日期。我會直接訂購date_mod,然後轉換SELECT條款中的輸出。