我的问题是,我只需要一次/唯一地对每种饮料(a.DRINK)做以下陈述,但我似乎做不到。
create table LOWEST as
select a.DRINK, min(b.PRICE), c.STREET, c.BLDG_NO
from ALLDRINKS a
left join SERVES b on a.DRINK = b.DRINK
left join LOCATED c on b.PUB = c.PUB
group by a.DRINK, c.STREET, c.BLDG_NO
我得到的当前结果
------------------------------------------------
| DRINK |min(b.PRICE)| STREET | BLDG_NO |
| VODKA | 7.10 | FAKE ST. | 123 |
| VODKA | 4.50 | OAK Ave. | 13 |
| VODKA | 8.30 | Rail RD. | 11 |
| RUM | 6.30 | Cherry RD. | 131 |
| RUM | 10.30 | TEST Pl. | 21 |
------------------------------------------------
我期望的位置:
------------------------------------------------
| DRINK |min(b.PRICE)| STREET | BLDG_NO |
| VODKA | 4.50 | OAK Ave. | 13 |
| RUM | 6.30 | Cherry RD. | 131 |
------------------------------------------------
如果您还可以解释需要做的事情背后的逻辑,那将对将来的工作大有帮助!先感谢您!-使用MYSQL Workbench 8.0
您可以使用表row_number()
中的SERVES
窗口函数来获取每个DRINK
的最低价格,因此您不需要group by
:
create table LOWEST as
select a.DRINK, b.PRICE, c.STREET, c.BLDG_NO
from ALLDRINKS a
left join (
select t.*
from (
select *, row_number() over (partition by DRINK order by price) rn
from SERVES
) t
where t.rn = 1
) b on a.DRINK = b.DRINK
left join LOCATED c on b.PUB = c.PUB
您想要serves
中的行具有每个drink
的最低价格,以及相应的location
。如果是这样,您不应该考虑aggregation,而应该考虑filtering。
您可以使用相关子查询在left join
中进行过滤:
create table lowest as
select d.drink, s.price, c.street, l.bldg_no
from alldrinks d
left join serves s
on s.drink = d.drink
and s.price = (select min(s1.price) from serves s1 where s1.drink = s.drink)
left join located l
on l.pub = s.pub
请注意,我重命名了您的表别名,以使它们更有意义,这使查询更易于遵循。