我有这样的SQL查询:
select tt.product_name, tt.countt
from (select ofr.product_name as product_name, count(*) as countt
from offers ofr
group by ofr.product_name) as tt
where 12 = (select max(tt.countt) from tt);
我的问题是在最后一行:sql无法识别表tt!
正如我在SQL / 92中所知,这种表的用法是有效的。但我不知道在后面的版本中我应该使用哪种替代方案。
我正在使用这个版本的MY-SQL:
mysql Ver 14.14 Distrib 5.7.25,适用于Linux(x86_64),使用EditLine包装器
更新:我想要tt中的行,它的“县”是tt中所有行的最大值。数字“12”是一个例子,因为根据我数据库中的数据,“count”列的最大值将是12
我不明白max()
打算做什么。如果这在MySQL中有效,我会感到惊讶。
也许你打算:
select tt.product_name, tt.countt
from (select ofr.product_name as product_name, count(*) as countt
from offers ofr
group by ofr.product_name
) tt
where 12 = tt.countt;
子查询对于此逻辑不是必需的。您可以使用HAVING
子句代替。
编辑:
如果你想要最大值,你可以使用ORDER BY
和LIMIT
:
select ofr.product_name as product_name, count(*) as countt
from offers ofr
group by ofr.product_name
order by countt desc
limit 1;
MySQL 5.x中唯一适用于我的解决方案需要重复查询。在MySQL 8.x中,您可以使用CTE(公用表表达式),但在5.x中不可用。
无论如何,这是有效的查询:
select x.*
from (
select product_name, count(*) as cnt
from offers
group by product_name
) x
join (
select max(cnt) as ct
from (
select product_name, count(*) as cnt
from offers
group by product_name
) y
) z on z.ct = x.cnt
结果:
product_name cnt
------------ ---
Daguerrotype 3
作为参考,我使用的数据是:
create table offers (
product_name varchar(30)
);
insert into offers (product_name) values ('Daguerrotype');
insert into offers (product_name) values ('Transistor radio');
insert into offers (product_name) values ('Victrola');
insert into offers (product_name) values ('Daguerrotype');
insert into offers (product_name) values ('Victrola');
insert into offers (product_name) values ('Daguerrotype');