我可以在父查询中对嵌入式查询的结果进行数学计算吗?

时间:2013-02-14 16:22:45

标签: mysql sql

考虑查询:

SELECT n.nid, 
    (select count(*) as count from view_log where id = n.nid) AS the_count,
    (the_count + 1) as the_bumped_count
   FROM node n

当我运行时,我得到Unknown column 'the_count' in 'field list'。有没有办法解决?似乎the_count应该在查询中可见并且可供使用,但显然不是。顺便说一下,我也试过SUM(the_count, 1),但也失败了。谢谢!

2 个答案:

答案 0 :(得分:2)

您无法使用在您希望对其进行计算的同一级别定义的ALIAS

SELECT n.nid, 
    (select count(*) as count from view_log where id = n.nid) AS the_count,
    ((select count(*) as count from view_log where id = n.nid) + 1) as the_bumped_count
   FROM node n

或更好地使用子查询,

SELECT  nid, 
        the_count, 
        the_count + 1 AS the_bumped_count
FROM
(   
    SELECT n.nid, 
            (select count(*) as count from view_log where id = n.nid) AS the_count
    FROM node n
) s

答案 1 :(得分:2)

我认为这也会有效,只需要你算一次:

SELECT nid, the_count, the_count+1 as the_bumped_count
FROM (
    SELECT n.nid,
        COUNT(v.*) the_count, 
    FROM node n
       LEFT JOIN view_log v on n.nid = v.id
    GROUP BY n.nid
) t

或者回到你的语法:

SELECT nid, the_count, the_count+1 as the_bumped_count
FROM (
    SELECT n.nid,
        (select count(*) as count from view_log where id = n.nid) AS the_count
    FROM node n
) t
祝你好运。