2013-02-14 42 views
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),但那也失敗了。謝謝!

回答

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 

祝你好運。

+0

子查詢方法最適合我 - 我發佈的代碼是我真正問題的簡化版本,但它很好地適應了真正的事情。謝謝! – 2013-02-14 16:49:23

+0

@JimMiller - np,很高興我們能夠! – sgeddes 2013-02-14 16:56:47

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 
相關問題