1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sqlのミニTips

Posted at

はじめに

業務で見かけたsqlについて、「こんなのあるんだ」と感じた点、2つまとめてみました。

1,Selectでしぼったデータを利用してjoinする

以下のテーブルを利用します

userテーブル

user_id user_name
1 Aさん
2 Bさん
3 Cさん

postテーブル

post_id post_user_id post_name
1 1 日記1
2 2 日記2
3 3 日記3
4 1 日記4
5 日記5
6 1 日記6

上記のテーブルでAさんが投稿した数の合計値をだしたい場合以下のように書けます。
ここでは簡単な例でjoin後にcount関数を使うこともできますが、より複雑な条件で
データを取得したい場合には効果を発揮しそうな書き方だと思いました。

select *
from sample_user
 INNER JOIN (
			select post_user_id ,count(post_user_id ) as post_user_count
			from  sample_post
			where post_user_id = 1
			GROUP BY post_user_id 
		)post_one
		ON post_one.post_user_id = sample_user.user_id

結果

user_id user_name post_user_id post_user_count
1 Aさん 1 3

2,Left Joinをすると重複する(ように見える)

以下のテーブルを利用します

adminテーブル

admin_id name_sei name_mei
1 田中 hoge
2 山田 huge

admin_categoryテーブル

admin_category_id admin_id
1 1
2 1
3 1

以下のsqlを流します。

SELECT	 ad.admin_id
		,ad.name_sei
		,ad.name_mei
		
FROM	admin ad
	LEFT JOIN admin_category adc
	ON adc.admin_id = ad.admin_id

結果

admin_id name_sei name_mei
1 田中 hoge
1 田中 hoge
1 田中 hoge

紐づいたadmin_idでjoinすると重複してるように見えます。
admin_categoryのデータをselectしていないのが原因です。
重複して表示されるのが正しいシステムの場合は、そのままで大丈夫ですが
この情報をひとまとめにしたい場合は、以下のようにDISTINCTを付け足して書くと1つのデータとなります。

SELECT DISTINCT ad.admin_id
        ,ad.name_sei
        ,ad.name_mei

FROM    admin ad
    LEFT JOIN admin_category adc
    ON adc.admin_id = ad.admin_id

終わりに

2つ紹介させていただきましたが、訂正点などあればご指摘いただけると幸いです。
left joinで複数なるケースがほかにもあった気がするのですが忘れました・・・w

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?