重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

MySQLのDBにmemberという下記テーブルがあります。

このテーブルには毎日同じ時刻にメンバーのfollower数が蓄積されていきます。

id, member_id, follower_count, date
1, 101, 55, 2019-01-24 19:12:01
2, 102, 123, 2019-01-24 19:12:01
3, 103, 10, 2019-01-24 19:12:01
4, 104, 5, 2019-01-24 19:12:01
5, 105, 88, 2019-01-24 19:12:01
6, 101, 70, 2019-01-25 19:12:01
7, 102, 80, 2019-01-25 19:12:01
8, 103, 50, 2019-01-25 19:12:01
9, 104, 150, 2019-01-25 19:12:01
10, 105, 55, 2019-01-25 19:12:01


やりたいことはphpとmysqlを使って

1. 日間のfollower数ランキング(follower_count数の差分で1位からランキング化)

2. 月間のfollower数ランキング(follower_count数の差分で1位からランキング化)

になります。

具体的にはphpで下記のように表示させたいと思っています。

■2019年1月24日~25日のメンバーfolloer数ランキング

  メンバー  folloer増減数
1位 104     +145
2位 103     +40
3位 101     +15
4位 105     -33
5位 102     -43


■2019年1月~2月のメンバーfolloer数ランキング

  メンバー  folloer増減数
1位 104     +xxx
2位 103     +xxx
3位 101     +xxx
4位 105     -xxx
5位 102     -xxx


どのようなsqlを書いたら(あるいはphp側で書いたら)上記のランキングを表示することができますか?

A 回答 (3件)

create table member(id int primary key, member_id int unique,name varchar(20));


insert into member values
(1,101,'安倍里美'),
(2,102,'五十嵐太郎'),
(3,103,'宇野次郎'),
(4,104,'太田智');

select
t1.id
,t1.member_id
,t3.name
,t1.follower_count-coalesce(t2.follower_count,0) as zougen
from tbl as t1
left join tbl as t2 on t1.member_id=t2.member_id
and t2.d='2019-01-24'
inner join member as t3
on t1.member_id=t3.member_id
where t1.d='2019-01-25'
order by zougen desc
    • good
    • 0
この回答へのお礼

何度もありがとうございました!助かりました。

お礼日時:2019/01/31 17:18

仮にこう



create table tbl(id int primary key, member_id int, follower_count int, d date,unique key(member_id,d));
insert into tbl values
(1, 101, 55, '2019-01-24'),
(2, 102, 123, '2019-01-24'),
(3, 103, 10, '2019-01-24'),
(4, 104, 5, '2019-01-24'),
(5, 105, 88, '2019-01-24'),
(6, 101, 70, '2019-01-25'),
(7, 102, 80, '2019-01-25'),
(8, 103, 50, '2019-01-25'),
(9, 104, 150, '2019-01-25'),
(10, 105, 55, '2019-01-25'),
(11, 106, 1, '2019-01-25'),
(12, 101, 1, '2019-01-23');

11番=1/25に初めてデータ登録された人
12番=もっと古いデータ

select
t1.id
,t1.member_id
,t1.follower_count-coalesce(t2.follower_count,0) as zougen
from tbl as t1
left join tbl as t2 on t1.member_id=t2.member_id
and t2.d='2019-01-24'
where t1.d='2019-01-25'
order by zougen desc
    • good
    • 0
この回答へのお礼

ありがとうございます。
すごいです。できました!

実行してみたら下記のように表示できました。
id, member_id, zougen
9 104 145
8 103 40
6 101 15
11 106 1
10 105 -33
7 102 -43

ここで、追加でお聞きしたいことがありまして(何度もすいません)

他のテーブル(nameテーブル)とさらにmember_idでjoinしたい場合、教えていただいたselect文にどのようにつなげたらいいでしょうか。

nameテーブル

id, member_id,  name
1,  101     安倍里美
2,  102     五十嵐太郎
3,  103     宇野次郎
4,  104     太田智

ここで質問するのではなく、新たに質問トピックを立てたほうがいいでしょうか。
どうかよろしくお願い致します。

お礼日時:2019/01/31 16:50

dateカラムがdatetimeなので結構面倒


投入タイミングで1秒でもずれると1日前がずれちゃいますが
date型に変えるなど対応はありですか?
    • good
    • 0
この回答へのお礼

はい!date型に変更できます。

お礼日時:2019/01/31 12:55

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!

関連するカテゴリからQ&Aを探す