2017-12-21 1 views
-1

私は2つのテーブルライターとブログを持っています。ライターテーブルには、ID列と名前列があります。ブログテーブルにはid、blog、writer_idがあります。私はもっとブログを書く作家を見つけなければなりません。mysqlでほとんどの本を書いた人を含むリストの著者を見つけるにはどうすればいいですか

+0

してください** [EDIT] **あなたの質問といくつかの追加[サンプルデータ](http://plaintexttools.github.io/plain-text-table/)とそのデータに基づいて予想される出力。 [**書式設定されたテキスト**](http://stackoverflow.com/help/formatting)ください、[** noスクリーンショット**](http://meta.stackoverflow.com/questions/285551/why-may -i-not-upload-images-of-code-on-so-asking-a-question/285557#285557)。 ** [編集] **あなたの質問 - コメントを投稿するコードや追加情報はありません**。 –

+0

@ThorstenKettner質問はタイトルにあります – tonypdmtr

答えて

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一部を変更することによって、あなたはなど

0

あなたはこのコードを試してみてくださいトップ2または3にトップ1から変更することができます。 私は本の同じ量を書いたseveralsライターが存在することができ、これは便利

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 
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のをあなたは別のアプローチを見つけることを余儀なくされている:著者

  • あたり

    1. カウントブックは、これらの
    2. 選択著者とその本だけ著者を保つ
    3. 再びカウントの最大数を決定しますブックカウントが最大書籍数に一致する
    4. 著者名を選択

    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 
    ) 
    );