如何从其他子查询中选择从字段别名派生的一些数据

时间:2014-12-18 23:41:52

标签: mysql

我有一个具有以下结构的查询:

SELECT *,
    (<sub-query>) AS `n_acts`,
    (<sub-query>) AS `n_ops`,
    `n_acts`/`n_ops` AS `score`
FROM `user`
WHERE `type` = '3'

但我一直收到以下错误:

  

SQLSTATE [42S22]:找不到列:1054未知列&#39; n_acts&#39;在&#39;字段列表&#39;

我需要计算score字段,因为我需要按该值对查询进行排序,如下所示:

SELECT *,
    (<sub-query>) AS `n_acts`,
    (<sub-query>) AS `n_ops`,
    `n_acts`/`n_ops` AS `score`
FROM `user`
WHERE `type` = '3'
ORDER BY `score` DESC
LIMIT 10

为什么MySQL无法识别我的字段别名?我该如何解决这个问题?最重要的是,建议这样做吗?

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT `inner_sub`.`n_acts`, `inner_sub`.`n_ops`, `inner_sub`.`n_acts`/`inner_sub`.`n_ops` AS `score`
FROM
    (SELECT *,
        (<sub-query>) AS `n_acts`,
        (<sub-query>) AS `n_ops`
    FROM `user`
    WHERE `type` = '3') AS `inner_sub`
ORDER BY `inner_sub`.`score` DESC
LIMIT 10