mysql:计算mysql中的别名字段

时间:2017-06-12 13:49:00

标签: mysql

我已经提到了:

How to use alias as field in mysql

&安培;

Adding MySQL alias fields together

我想对别名字段进行一些计算但是会抛出错误

以下是我的查询

 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"

但它会抛出错误

此选择行中的错误

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 

,错误是

  

致命错误:未捕获的异常'异常'消息'未知   专栏'明星'在'字段列表'查询:选择j。,(选择总和(星星)   来自ratingstar,其中jobid = j.id)作为星星,(从中选择计数())   ratingtar,其中jobid = j.id)作为计数,((星/(计数* 5)* 5))作为评级   来自作业j内部联接提议p on p.jobid = j.id内部联接   us_signup u on u.id = p.userid inner join hired h on h.proposalid = p.id   其中h.status ="完成"'在   第3637行的E:\ wamp \ www \ sugumar \ mysuite \ includes \ classes \ MysqliDb.php

3 个答案:

答案 0 :(得分:0)

我认为你最后错过了a)

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

编辑*你没有错过它,你刚刚在开头添加了一个无用的

(stars/(count*5)*5)

答案 1 :(得分:0)

Count是一个保留的SQL术语,如果你想使用is作为一个字段,你应该这样做:

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"

答案 2 :(得分:0)

由于count是保留字/函数,因此需要使用反引号引用它:

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"