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

次のSQL文を実行します。

create table1 (id, english)
insert table1 (1,"foo")
insert table1 (2,"bar")

create table2 (id, japanese)
insert table2 (1, "ふー")
insert table2 (2, "ばー")

SQL文法としては誤ってますが、成功したとします。


いま、select id from table1 where english = 'foo';
で1が得られます。

いま、select japanese from table2 where id = 1;
で"ふー"が得られます。

これを一つのSQLite3のselect文で実現できないでしょうか。

select japanese from table2 where id = (select id from table1 where english = 'foo');

で良いですか?


カテゴリ選択にSQLiteが無いのは、人気が無いからですかね。

A 回答 (2件)

>select japanese from table2 where id = (select id from table1 where english = 'foo');



englishがユニークでない場合
select id from table1 where english = 'foo'
で得たidは1つとは限りません。
上記で2つ以上のidが返ってきたときid=・・・は文法的にエラーになります。
どうしてもサブクエリでやりたいならinをつかうことになるでしょう
(SQLiteに該当する文法があるなら)

select japanese from table2 where id in (select id from table1 where english = 'foo');

#1さんのSQL文で問題ありませんが、
ロジック的には絞ったtable1からtable2の値を得たいので

select japanese from table1 inner join table2 on table1.id = table2.id and english = 'foo';

の方が、より直観的かもしれませんね。
ちなみにMySQLでテストする限り適切なインデックスさえ貼ってあれば、
効率は変わらないみたいです。
    • good
    • 0
この回答へのお礼

みなさん、返答有り難うございます

よく分かりました
現在、データ登録中(もう、三回失敗していますが...)です。成功したら試してみます。

今後もおねがいします

お礼日時:2015/01/26 16:57

サブクエリを使うその方法でもいいですが、


一般的には結合(join)を使うし、その方が高速な場合が多いと思います。

select japanese from table1 inner join table2 on table1.id = table2.id where english = 'foo';
    • good
    • 0

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