我可以使用从SELECT子句中的子查询返回的列对结果进行排序吗?

时间:2016-01-12 13:55:37

标签: mysql

使用下面的例子,这不是确切的代码,只是我想要实现的一个例子:

该查询将用于返回五个访问量最大的网页,以及该网页已注册的访问次数。

SELECT
     page_instance.name AS 'page name',

     /* Sub Query I wish to sort by */
     (
       SELECT COUNT(*) 
       FROM visitor_event 
       WHERE page_instance.id = visitor_event.item_id
     ) AS 'visit count'

    FROM item_event

    LEFT JOIN visitor_event_type ON visitor_event_type.id =  visitor_event_type_id
    LEFT JOIN page_instance ON page_instance.id = visitor_event.item_id
    LEFT JOIN page ON page.id = page_instance.page_id

    WHERE visitor_event_type.handle = 'viewed'
    AND page_instance.name != 'NULL'
    GROUP BY page.id
    ORDER BY 'visit count' DESC /* Where its going wrong */
    LIMIT 5

目前,查询运行时没有错误,但不会按“访问次数”列进行排序。

我见过类似的查询将子查询放在FROM子句中。我不明白这个的原因,因为我可能想要其他列的其他子查询(对于最大/最小结果等)。我不反对这个想法,我只是不明白它的原因

1 个答案:

答案 0 :(得分:2)

这样做:

SELECT temp.* FROM (SELECT
     page_instance.name AS 'page name',
    (
       SELECT COUNT(*) 
       FROM visitor_event 
       WHERE page_instance.id = visitor_event.item_id
     ) AS 'visit_count'

    FROM item_event

    LEFT JOIN visitor_event_type ON visitor_event_type.id =  visitor_event_type_id
    LEFT JOIN page_instance ON page_instance.id = visitor_event.item_id
    LEFT JOIN page ON page.id = page_instance.page_id

    WHERE visitor_event_type.handle = 'viewed'
    AND page_instance.name != 'NULL'
    GROUP BY page.id
    LIMIT 5 ) as temp ORDER BY temp.visit_count DESC