0

考虑以下查询:

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),但也失败了。谢谢!

4

2 回答 2

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
于 2013-02-14T16:23:27.667 回答
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

祝你好运。

于 2013-02-14T16:26:10.153 回答