回答編集履歴

1 追記

sk_3122

sk_3122 score 1015

2018/05/11 10:29  投稿

```sql
-- ★テーブル代わりのWITH句
WITH
tableA AS (
SELECT 1 AS brand, 1200 AS code UNION ALL
SELECT 1 AS brand, 1201 AS code UNION ALL
SELECT 1 AS brand, 1202 AS code UNION ALL
SELECT 2 AS brand, 1200 AS code UNION ALL
SELECT 2 AS brand, 1201 AS code UNION ALL
SELECT 2 AS brand, 1202 AS code
),
tableB AS (
SELECT 1 AS brand, 1201 AS code, 'A' AS name UNION ALL
SELECT 2 AS brand, 1202 AS code, 'B' AS name
)
-- ★SELECT ここから
select
 ta.brand
, ta.code
, tb.name
from tableA as ta
left join tableB as tb on (
 ta.brand = tb.brand and
 ta.code = tb.code
)
```
- tableA と tableB の結合条件に code を追加
- `join tableB` → `left join tableB`
でしょうか
でしょうか
-----
あ、yambejp さんの回答まんまでしたね。
yambejp さんが書かれた SQL をコピペしても ↑ と同じ結果になりましたよ
自分で書いた時はなにか書き間違えてたのかもしれませんね?

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る