与其他数据一起获取最大值
我必须来问这个,因为我已经生气、哭泣等等,因为这真的要了我的命。我讨厌 SQL。但这是必须要做的。网站使用 SQL。
我有这些表(缩短为必要的而不是真正的 SQL):
CREATE TABLE deliverer(d_id INT PRIMARY KEY, name VARCHAR(80));
CREATE TABLE article(a_id INT PRIMATY KEY, brand VARCHAR(80));
CREATE TABLE delivers(d_id FOREIGN KEY(deliverer), a_id FOREIGN KEY(article));
对于每个品牌
,我需要那些提供最多文章的交付者
。经过仅仅两个小时的思考,我已经走到了这一步:
SELECT brand, MAX(cnt)
FROM
(SELECT COUNT(a.a_id) AS cnt, a.brand, d.d_id, d.name
FROM derliverer d, delivers l, article a
WHERE a.a_id = l.a_id AND l.d_id = d.d_id
GROUP BY a.brand, d.d_id, d.name)
GROUP BY brand;
我真的、真的、真的不明白 SQL 是为什么它不允许我GROUP BY Brand
和 SELECT
d.name、d.d_id
。这确实没有任何意义。
在我跳出窗户之前请帮助我。
I have to come and ask this because I'm already angry and crying and everything, because this really kills me. I hate SQL. But it has to be done. Website uses SQL.
I have these tables (shortened to the necessessary and not real SQL):
CREATE TABLE deliverer(d_id INT PRIMARY KEY, name VARCHAR(80));
CREATE TABLE article(a_id INT PRIMATY KEY, brand VARCHAR(80));
CREATE TABLE delivers(d_id FOREIGN KEY(deliverer), a_id FOREIGN KEY(article));
I need, for each brand
those deliverers
that deliver the most articles. I've come as far as this, after only two hours of mind twisting:
SELECT brand, MAX(cnt)
FROM
(SELECT COUNT(a.a_id) AS cnt, a.brand, d.d_id, d.name
FROM derliverer d, delivers l, article a
WHERE a.a_id = l.a_id AND l.d_id = d.d_id
GROUP BY a.brand, d.d_id, d.name)
GROUP BY brand;
What I really, really, really don't get about SQL is why it does not let me GROUP BY brand
and SELECT
the d.name, d.d_id
. It really makes no sense.
Please help me before I jump out of the window.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为如果这样做,计数将针对每个不同的 d.name、d.d_id。这不是你想要的。
您肯定想阅读一些教程,了解分组依据的工作原理。
在这种情况下,你需要类似的东西:
Because if you do, the count will be for each distinct d.name, d.d_id. This is not what you want.
You definitely want to read some tutorials on how a group by works.
In this case you need something like: