[英]The grouping and the largest number in MySql
下午好! 我開始學習MySql並遇到問題:
查詢錯誤:錯誤:ER_WRONG_FIELD_WITH_GROUP:SELECT列表的表達式#1不在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
要獲得每種產品的最低價格,您可以執行以下操作:
select p.*
from price p
where p.price = (select min(p2.price) from price p2 where p2.product_id = p.product_id);
其他join
將引入名稱而不是id
。
要獲得每種產品一行:
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;
您可以對按產品和地區分組的最高價格使用聯接
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
我會用類似的東西:
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),然后為每種產品/價格組合找到最小(即第一個字母)區域
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.