Question

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 !

Was it helpful?

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

OTHER TIPS

You can't use an alias that you have given in the select list like that as a result the buyTickets is not known to be used in another calculation. One way to fix this would be to use a subquery:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top