Search code examples
mysqlsubquerymysql-error-1054

Mysql subquery calculation (Error 1054)


This is what I want to do (simplified query) :

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

But when I do this, I have this message :

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

I'm confusing. Please help me.

Thanks !


Solution

  • the column buyTickets is not defined there (alias and not table column). either repeat the count, or use an inner query:

    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