在MySQL中使用ORDER BY中的别名列

时间:2016-03-13 03:56:16

标签: mysql sql-order-by

我创建了一个SQL查询来分组,它具有值并按别名排序记录,如下所示:

SELECT * 
FROM   `timeline`, 
       (SELECT Max(mycountview) 
        FROM   (SELECT Count(id_timeline) AS mycountview
                FROM   `timeline` 
                WHERE  type_timeline = '1' 
                GROUP  BY mediaid)AS mycountview)AS max_mycountview
WHERE  type_timeline = '1' 
GROUP  BY mediaid 
HAVING Count(id_timeline) < max_mycountview
ORDER  BY max_mycountview DESC 
LIMIT  0, 5 

但我收到了错误:

  

未知栏&#39; max_mycountview&#39;在&#39;订单条款&#39;


如何解决?

1 个答案:

答案 0 :(得分:2)

您需要将子查询移动到select语句而不是from子句:

SELECT *, 
        (SELECT Max(mycountview) 
        FROM   (SELECT Count(id_timeline) AS mycountview
                FROM   `timeline` 
                WHERE  type_timeline = '1' 
                GROUP  BY mediaid)AS mycountview) AS max_mycountview
FROM   `timeline`
WHERE  type_timeline = '1' 
GROUP  BY mediaid 
HAVING Count(id_timeline) < max_mycountview
ORDER  BY max_mycountview DESC 
LIMIT  0, 5 

实际上在重新阅读您的查询后,我不相信这将是最有效的方法。您的查询在表之间执行cross join。但是子查询没有相关性 - 它为每列返回相同的值。在这种情况下,您只需要在子查询中定义列名,以便能够在havingorder by子句中访问它:

SELECT * 
FROM   `timeline`,
       (SELECT Max(mycountview) max_mycountview   <!--Define Column Alias Here
        FROM   (SELECT Count(id_timeline) mycountview
                FROM   `timeline` 
                WHERE  type_timeline = '1' 
                GROUP  BY mediaid) t) y
WHERE  type_timeline = '1' 
GROUP  BY mediaid 
HAVING Count(id_timeline) < max_mycountview
ORDER  BY max_mycountview DESC 
LIMIT  0, 5