MySql order by子句不起作用
在mysql查询中,我使用了MySql order by子句不起作用,mysql,sql-order-by,Mysql,Sql Order By,在mysql查询中,我使用了orderby,但它不起作用 当我这么做的时候 SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id FROM threads t LEFT JOIN comments c ON c.thread_id = t.id INNER JOIN (
orderby
,但它不起作用
当我这么做的时候
SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id
FROM threads t
LEFT JOIN comments c ON c.thread_id = t.id
INNER JOIN (
SELECT thread_id, MAX(date_sent) recent_date, MAX(is_answer) has_answer
FROM comments
GROUP BY thread_id
) d ON c.id IS NULL OR (d.thread_id = c.thread_id AND d.recent_date = c.date_sent)
LEFT JOIN thread_images i ON t.id = i.thread_id
WHERE t.user_id = t.user_id
GROUP BY t.id
ORDER BY d.recent_date DESC
LIMIT 0, 10
它没有正确的顺序。但如果我这样做:
SELECT *
FROM (
SELECT t.id,t.user_id,t.title,c.comment,d.has_answer,IF(c.id IS NULL, t.date_created, d.recent_date) recent_date,MIN(i.id) image_id
FROM threads t
LEFT JOIN comments c ON c.thread_id = t.id
INNER JOIN (
SELECT thread_id, MAX(date_sent) recent_date, MAX(is_answer) has_answer
FROM comments
GROUP BY thread_id
) d ON c.id IS NULL OR (d.thread_id = c.thread_id AND d.recent_date = c.date_sent)
LEFT JOIN thread_images i ON t.id = i.thread_id
WHERE t.user_id = t.user_id
GROUP BY t.id
LIMIT 0, 10) qwerty
ORDER BY recent_date DESC
然后它就起作用了。为什么上面的方法不起作用,第二种方法是解决这个问题的最好方法吗
谢谢这两种说法是按两种不同的东西排序的 第二条语句根据选择列表中表达式的结果排序 但是第一条语句指定了内联视图
d
返回的recent_date
值的排序;如果从最近日期前面删除“
”,则ORDER BY
子句将引用分配给SELECT列表中表达式的别名,就像第二条语句一样
由于recent_date
是选择列表中表达式的别名,因此这两个值是等效的:
ORDER BY recent_date
ORDER BY IF(c.id IS NULL, t.date_created, d.recent_date)
^^
但这些都与:
ORDER BY d.recent_date
^^
请注意,GROUP BY
子句的非标准使用可能会掩盖查询丢弃的一些最近日期的值。groupby
子句的使用是对SQL标准的MySQL扩展;大多数其他关系数据库都会在该语句中抛出错误。通过启用ONLY\u FULL\u GROUP\u by
SQL模式,可以让MySQL抛出相同类型的错误
Q第二种说法是解决这个问题的最佳方法吗
A如果该语句保证返回的结果集符合您的规范,那么这是一种可行的方法。(一个缺点是内联视图查询的开销。)
但我强烈怀疑第二种说法实际上只是掩盖问题,而不是真正解决问题
ORDER BY d.recent_date
^^