2024年10月22日 16:25 by wst
database在常规的查询中,我们知道用where过滤得到想要的数据。
在group by之后的数据,是否也可以用where进行过滤呢?
比如有这么一个需求:查出某个桌子点的所有菜品的价格总和;
SQL语句如下:
select table_id,sum(total_price) as receivable from user_cart group by table_id where table_id=62;
执行结果:
mysql> select table_id,sum(total_price) as receivable from user_cart group by table_id where table_id=62;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where table_id=62' at line 1
它说有语法错误,看来不能这么写。
通过搜索发现,在group by后想过滤数据,需要使用having关键字;正确的SQL如下:
select table_id,sum(total_price) as receivable from user_cart group by table_id HAVING table_id=46;
执行结果:
mysql> select table_id,sum(total_price) as receivable from user_cart group by table_id HAVING table_id=46;
+----------+------------+
| table_id | receivable |
+----------+------------+
| 46 | 25300 |
+----------+------------+
1 row in set (0.00 sec)
砥砺前行,一个热爱分享,热爱尝试的小鲤鱼!