0

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

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'

我很困惑。请帮我。

谢谢 !

4

2 回答 2

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
于 2013-06-06T14:49:58.640 回答
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
于 2013-06-06T14:51:51.653 回答