首页 文章资讯内容详情

我们可以在MySQL WHERE子句中使用SUM()函数的结果吗

2026-06-04 1 花语

我们可以在MySQL中使用HAVING子句而不是WHERE。让我们首先创建一个表-

create table DemoTable ( Name varchar(50), Price int );

使用插入命令在表中插入一些记录-

insert into DemoTable values(Chris,30); insert into DemoTable values(David,40); insert into DemoTable values(Chris,10); insert into DemoTable values(Mike,44); insert into DemoTable values(David,5);

使用select语句显示表中的所有记录-

select *from DemoTable;

这将产生以下输出-

+-------+-------+ | Name | Price | +-------+-------+ | Chris | 30 | | David | 40 | | Chris | 10 | | Mike | 44 | | David | 5 | +-------+-------+ 5 rows in set (0.00 sec)

以下是在HAVING子句中使用SUM()函数的结果的查询-

select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;

这将产生以下输出-

+-------+-------------+ | Name | Total_Price | +-------+-------------+ | David | 45 | | Mike | 44 | +-------+-------------+ 2 rows in set (0.03 sec)