0

I already referred :

How to use alias as field in mysql

&

Adding MySQL alias fields together

I want to some calculations on alias fields but it throws error

following is my query

 select j.*,
    (select sum(stars) from ratingstar where jobid=j.id) as stars,
    (select count(*) from ratingstar where jobid=j.id) as count,
    ((stars/(count*5)*5)) as rating     //I have problem here if I remove this it works fine 
from jobs j inner join proposals p on p.jobid=j.id 
            inner join us_signup u on u.id=p.userid 
            inner join hired h on h.proposalid=p.id 
            where h.status="finished"

But it throws error

error in this select line

select j.*,
    (select sum(stars) from ratingstar where jobid=j.id) as stars,
    (select count(*) from ratingstar where jobid=j.id) as count,
    ((stars/(count*5)*5)) as rating     //I have problem here if I remove this it works fine 

and error is

Fatal error: Uncaught exception 'Exception' with message 'Unknown column 'stars' in 'field list' query: select j.,(select sum(stars) from ratingstar where jobid=j.id) as stars,(select count() from ratingstar where jobid=j.id) as count,((stars/(count*5)*5)) as rating from jobs j inner join proposals p on p.jobid=j.id inner join us_signup u on u.id=p.userid inner join hired h on h.proposalid=p.id where h.status="finished"' in E:\wamp\www\sugumar\mysuite\includes\classes\MysqliDb.php on line 3637

Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77

3 Answers3

0

i think you missed a ) at the end

((stars/(count*5)*5))

edit* you didnt miss it,you just added an useless one at the beginning

(stars/(count*5)*5)
frankiehf
  • 180
  • 2
  • 14
0

Count is a reserved SQL term, if you want to use is as a field, you should do it like this:

select j.*,
    (select sum(stars) from ratingstar where jobid=j.id) as stars,
    (select count(*) from ratingstar where jobid=j.id) as count,
    ((stars/(`count`*5)*5)) as rating     //I have problem here if I remove this it works fine 
from jobs j inner join proposals p on p.jobid=j.id 
            inner join us_signup u on u.id=p.userid 
            inner join hired h on h.proposalid=p.id 
            where h.status="finished"
Osuwariboy
  • 1,335
  • 1
  • 14
  • 29
0

Since count is a reserved word/function, you need to quote it using backticks:

select j.*,
    (select sum(`stars`) from `ratingstar` where `jobid` = j.`id`) as `stars`,
    (select count(*) from `ratingstar` where `jobid` = j.`id`) as `count`,
    (`stars` / (`count` * 5) * 5) as `rating`
from `jobs` j 
inner join `proposals` p 
    on p.`jobid` = j.`id` 
inner join `us_signup` u 
    on u.`id` = p.`userid` 
inner join `hired` h 
    on h.`proposalid` = p.`id` 
where h.`status` = "finished"
Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40