0

我有一个这样的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”是一个例子,因为根据我数据库中的数据,“count”列的最大值将为 12

4

2 回答 2

0

在 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');
于 2019-04-08T19:59:33.847 回答
0

我不明白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 BYand 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;
于 2019-04-08T19:36:25.053 回答