来自 SQL/92 的查询在更高版本中不起作用



我有一个这样的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,适用于使用 EditLine 包装器的 Linux (x86_64(

更新:我希望 tt 中"countt"的行是 tt 中所有行的最大值。数字"12"就是一个例子,因为根据我的 dabase 中的数据,"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 BYLIMIT

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');

最新更新