开发者

Referencing a column that does not exist

I have an SQLite3 query that blows up because a column does not exist. Here is a simplified version of the query:

SELECT
    colA,
    colB,
    (colA + colB) colC,
    (colA + colB + colC) colD
FROM
    myTable

The query is exploding when colC is referenced on the line to compute colD. I was hoping that since I defined colC before colD, it would work.

What can I do to achieve wh开发者_如何转开发at I'm wanting? I need colC to be computed at the time the query is ran.


You can use a subquery:

SELECT
    colA,
    colB,
    colC,
    (colA + colB + colC) colD
FROM (
    SELECT
        colA,
        colB,
        (colA + colB) colC
    FROM
        myTable
) x


Per this:

SQLite does not (currently) make any promises about column names on
queries that omit the AS clause.

I would suggest trying this:

SELECT
    colA,
    colB,
    (colA + colB) AS colC,
    (colA + colB + colC) AS colD
FROM
    myTable

It's possible that the computed value does not get aliased until the resultset is ready to go... or some other such timing issue. Why not simply repeat the calculation like this:

SELECT
    colA,
    colB,
    (colA + colB) colC,
    (colA + colB + colA + colB) colD
FROM
    myTable

This way you avoid having to read the aliased, computed column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜