Mysql子查询计算(错误1054)

时间:2013-06-06 14:46:40

标签: mysql subquery mysql-error-1054

这就是我想要做的(简化查询):

SELECT
 FOO.id,
 FOO.maxTickets,
 (SELECT COUNT(*) countx FROM barfoo BAR WHERE BAR.idt = FOO.id) buyTickets,
 (FOO.maxTickets - buyTickets) leftTickets
FROM
 foobar FOO
ORDER BY
 FOO.leftTickets ASC

但是当我这样做时,我有这样的信息:

   #1054 - Unknown column 'buyTickets' in 'field list'

我很困惑。请帮帮我。

谢谢!

2 个答案:

答案 0 :(得分:3)

您不能使用您在选择列表中指定的别名,因此不知道buyTickets是否在另一个计算中使用。解决这个问题的一种方法是使用子查询:

select id, 
    maxTickets, 
    buyTickets, 
    maxTickets - buyTickets as leftTickets
from
(
     SELECT FOO.id,
        FOO.maxTickets,
        (SELECT COUNT(*) countx 
             FROM barfoo BAR WHERE BAR.idt = FOO.id) buyTickets
    FROM foobar FOO
) d
ORDER BY leftTickets ASC

答案 1 :(得分:3)

列buyTickets没有在那里定义(别名而不是表列)。要么重复计数,要么使用内部查询:

SELECT
    id,
    maxTickets,
    (SELECT COUNT(*) countx FROM barfoo BAR WHERE BAR.idt = FOO.id) buyTickets,
    (FOO.maxTickets - (SELECT COUNT(*) countx FROM barfoo BAR WHERE BAR.idt = FOO.id)) leftTickets
FROM
    foobar FOO
ORDER BY
    leftTickets ASC