douxunzui1519 2009-10-22 10:09
浏览 125
已采纳

可以在WHERE子句中计算列别名吗?

First off, I'm not an expert with MySQL queries, and I can't seem to find a solution to my problem.

Example:

SELECT SUM(IF(table1.col1<4,1,0)) AS score WHERE score>0 GROUP BY table1.col2

The above would give an error as the column score does not exist in table1.

This is my workaround:

SELECT SUM(IF(table1.col1<4,1,0)) AS score GROUP BY table1.col2

Then checking each row in PHP

if($row['score']>0){...

There is a performance issue as I'm looping through rows that I know I will not need, ideally I need to ignore those rows within the query.

My understanding is that the WHERE clause is triggered for each row of the table, not the grouped row.

Is there a way to do this?

  • 写回答

2条回答 默认 最新

  • dougou5852 2009-10-22 10:18
    关注

    Having support column aliases, so you can do this:

    SELECT SUM(IF(table1.col1<4,1,0)) AS score
    GROUP BY table1.col2
    HAVING score > 0
    

    and you can simplify it as you're trying to count rows where col1 < 4:

    SELECT COUNT(table1.col1) AS score
     WHERE table1.col1 < 4
    GROUP BY table1.col2
    HAVING score > 0
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀