分组和MySql中的最大数字

时间:2018-01-22 15:44:28

标签: mysql sql select grouping

下午好! 我开始研究MySql并面临一个问题:

  

查询错误:错误:ER_WRONG_FIELD_WITH_GROUP:SELECT的表达式#1   list不在GROUP BY子句中,并包含非聚合列   'test.product.name',它在功能上不依赖于列   GROUP BY子句;这与sql_mode = only_full_group_by

不兼容

我用这个网站来研究https://www.db-fiddle.com/f/xxV16kmnZKmPktUdMSK6xZ/0

我的任务是: 找到每个产品价格最低的地区。如果有多个区域具有相同的价格,请按字母顺序选择第一个区域。

我的表:

create table product(id int, name varchar(99));
create table region(id int, name varchar(99));
create table price(productId int, regionId int, price decimal(9, 2));

insert into product values(1, 'Crab');
insert into product values(2, 'Crayfish');

insert into region values(1, 'Kiev');
insert into region values(2, 'Kharkov');
insert into region values(3, 'Lvov');

insert into price values(1, 1, 100);
insert into price values(1, 2, 100);
insert into price values(1, 3, 200);
insert into price values(2, 1, 200);
insert into price values(2, 2, 100);
insert into price values(2, 3, 100); 

我的选择:

select product.name 'product', price.price, region.name 'Region name' 
from price
left join product on product.id = price.productId
left join region on region.id = price.regionId
where price.price != 0
group by region.name
having max(price.price)
order by region.name

预期结果:

product region  price
Crab    Kharkov 100
Crayfish    Kharkov 100

3 个答案:

答案 0 :(得分:0)

要获得每种产品的最低价格,您可以:

select p.*
from price p
where p.price = (select min(p2.price) from price p2 where p2.product_id = p.product_id);

其他join会引入名称而不是id s。

每个产品获得一行:

select p.product_id, p.price, min(r.name)
from price p join
     region r
     on p.regionId = r.id
where p.price = (select min(p2.price) from price p2 where p2.product_id = p.product_id)
group by p.product_id, p.price;

答案 1 :(得分:0)

您可以按产品和地区分组的最高价格使用联接

select t.product, price.price, t.region
from price
INNER JOIN ( 
select price.productID, price.regionId, product.name product, 
          max(price.price) max_price, region.name Region 
from price
left join product on product.id = price.productId
left join region on region.id = price.regionId
where price.price != 0
group by product.name , 
    region.name,
    price.productID,
    price.regionId ) t on t.productId = price.productId  
      and t.regionId = price.regionId and t.max_price =  price.price

答案 2 :(得分:0)

我使用类似的东西:

select
  p2.name as product,
  (
    select min(r.name)
    from
      price as c2
      inner join region as r on c2.regionid = r.id
    where c2.productId = t.id and c2.price = t.price) as region,
  t.price
from
  product as p2
  inner join (
    select
      p.id,
      min(c.price) as price
    from
      product as p
      left outer join price as c on p.id = c.productId
    group by p.id) as t on p2.id = t.id

主要思想是为每个产品(子查询t)获得最低价格,然后为每个产品/价格组合找到最小(即按字母顺序排列)的区域