私は3つのテーブルを持っています
students: first_name, last_name, high_school_id, other_high_school
high_schols: id, title
other_high_schools: id, title, student_id
各生徒のリストを次の情報とともに表示したい:名、姓、高校
high_schoolsテーブルには、生徒が選択できる高校のリストが事前に入力されています。高校が見つからない場合は、[その他の高校]フィールドに高校を入力します。生徒がフォームを送信すると、情報が保存され、students.other_high_schoolフィールドが1に設定され、高校のタイトルとともにID(student.id = other_high_school.student_id)がother_high_schoolsテーブル(other_high_school.title)に保存されます。
select
first_name, last_name, hs.title as high_school
from
students s
left join
high_schools hs
on
s.high_school_id = hs.id
これはfirst_name、last_name、high_schoolを返しますが、そのクエリを変更して、students.other_high_school = 1かどうかを検出し、high_schoolsテーブルではなくother_high_schoolに参加することはできますか?
これは機能しませんが、私が達成しようとしていることを説明するのに役立つはずです。
select
first_name, last_name, hs.title as high_school
from
students s
CASE s.other_high_school
WHEN 0 THEN
left join
high_schools hs
on
s.high_school_id = hs.id
WHEN 1 THEN
left join
other_high_school hs
ON
s.id = hs.student_id
ELSE
left join
other_high_school hs
ON
s.id = hs.student_id
END CASE
解決済み
select
first_name, last_name,
IF(s.other_high_school = 1, ohs.title, hs.title) high_school
from
students s
left join
high_schools hs
on
s.high_school_id = hs.id
left join
other_high_schools ohs
on
s.id = ohs.student_id