我有两个表作家和博客。 Writer表有id和name列。博客表有id,blog和writer_id。我必须找到写更多博客的作家。
答案 0 :(得分:0)
我已根据您的简短描述创建了一个示例模式,并根据该模式提供了答案。
create table writer(id int,name text);
create table blog(id int,writer_id int,blog text);
insert into writer values
(1,'Writer A'), (2,'Writer B'), (3,'Writer C'), (4,'Writer D'),
(5,'Writer E'), (6,'Writer F'), (7,'Writer G');
insert into blog values
(1,1,'Blog 1'), (2,1,'Blog 2'), (3,3,'Blog 3'), (4,3,'Blog 4'),
(5,2,'Blog 5'), (6,3,'Blog 6'), (7,3,'Blog 7'), (8,6,'Blog 8'),
(9,4,'Blog 9');
select w.name,count(b.id) no_of_books
from writer w join blog b on w.id = b.writer_id
group by w.id
order by no_of_books desc
limit 1;
通过更改limit
部分,您可以从顶部1更改为顶部2或3等。
答案 1 :(得分:0)
您应该尝试使用此代码。 我希望这有用
select
a.name, Max(b.highest)
from writer as a
left join(
select
count(*)as highest,
writer_id
from blog
GROUP BY writer_id
) as b on a.id = b.writer_id
答案 2 :(得分:0)
可能有几位作家写过相同数量的书籍。所以我们需要一个允许联系的限制条款。
标准SQL查询:
select *
from writer
where id in
(
select writer_id
from blog
group by writer_id
order by count(*) desc
fetch first rows with ties
);
但是,MySQL的LIMIT
不允许绑定。人们可以通过他们的书数对作者进行排名来达到同样的目的。 MySQL虽然没有RANK
等排名功能。
因此,对于MySQL,您不得不寻找另一种方法:
MySQL查询:
select *
from writer
where id in
(
select writer_id
from blog
group by writer_id
having count(*) =
(
select count(*)
from blog
group by writer_id
order by count(*) desc
limit 1
)
);