在下面的SQL语句中,结果将不按顺序返回。如果它们按升序或降序排列则有意义,但似乎此处没有订单。
有关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
答案 0 :(得分: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
答案 1 :(得分:1)
它将您格式化的日期字符串排序为字符串,并且您希望将它们命名为日期。我会直接按date_mod
订购,然后转换SELECT
子句中的输出。