hacca8

SQL文のメモ

よく使うSQL文をメモします。
この記事は随時更新していきます。

文字列で検索

  • 対象テーブルの列A、Bにkey01かkey02があれば抽出
select
    *
  , concat(ifnull('column_a',''),'_',ifnull('column_b','')) as for_search_field
from
    'table_name'
where
    for_search_field like '%key01%'
    or for_search_field like '%key02%'

フィールドで検索

  • テーブルAのidと一致するテーブルBのレコードを抽出
select
    'table_a'.'id'
  , 'table_b'.*
from
    'table_a'
    inner join 'table_b'
        on 'table_a'.'id' = 'table_b'.'id'
  • テーブルA、Bを比較して、Aにだけあるidを抽出
select
    'table_a'.'id'
  , 'table_b'.'id'
from
    'table_a'
    left outer join 'table_b'
        on 'table_a'.'id' = 'table_b'.'id'
where
    'table_b'.'id' is null

結果を全件見たい場合はwhere句を外します。
その場合、結果のテーブルBのidが空白のレコードが、テーブルAのみのidです。

結合して抽出

  • テーブルAのレコード毎に、テーブルBのレコードを追加して抽出

例:

# テーブルA
id
1
2
3

# テーブルB
shop_id | shop_name
001     | AAA

# 結果
id | shop_id | shop_name
1  | 001     | AAA
2  | 001     | AAA
3  | 001     | AAA
select
    'table_a'
  , 'table_b'
from
    'table_a'
    cross join 'table_b'