我正在嘗試編寫一個SQL查詢,它將根據跨越其他幾個表的數據收集某個表中的某些數據。這部分很容易。不幸的是,我還需要從第二張表中恢復數據,這需要通過左連接來完成。如何用where子句寫一個左連接限制多個表的左手部分?
如果我只是做一個左連接,e。 G。
select *
from table_A A
left join table_B B on A.id=B.id
一切都很好。我可以在where子句安全足夠的補充,像
where A.id>5
當我嘗試對左側多個表中出現的問題,例如
select *
from table_A, table_C
left join table_B on A.id=B.id
where table_A.id=table_C.id
突然, A.id不再是公認的專欄。我嘗試改變它,以便我選擇A.id作爲foo,然後在foo = B.id上執行,但foo也不會被識別。 (在'on子句'中未知列'bla')
雖然有很多參考文獻可以解釋如何執行聯接子句,並且有些示例甚至使用簡單的where子句,但我找不到任何聯合一個連接子句,一個where子句和左邊的多個表。
有關問題背景:
我原來的查詢是:
select SQL_CALC_FOUND_ROWS tutor_user.username
, tutor_user.userid
, tutor_tutor.rate
, tutor_user.username
from tutor_user
, tutor_attends
, tutor_tutors_in
, tutor_subject
, tutor_tutor
where tutor_user.userid=tutor_attends.userid
and tutor_attends.schoolid=80
and tutor_tutors_in.userid=tutor_user.userid
and tutor_tutors_in.subjectid=tutor_subject.subjectID
and tutor_subject.name='Aerospace Studies'
and tutor_tutor.userid=tutor_user.userid //ERROR
LIMIT 0, 15
不幸的是,有沒有保證tutor_tutor信息將存在爲每個用戶 - 這是從糟糕的決策早期堅持一個小小的瑕疵在網站/數據庫設計週期中。所以,簡單的解決方案是將它變成一個連接。
問題是,我找不到任何好的教程來解釋如何將聯接與where子句相結合。我盡力想出了以下內容:
select SQL_CALC_FOUND_ROWS tutor_user.username
, tutor_user.userid
, tutor_tutor.rate
, tutor_user.username
from tutor_user
, tutor_attends
, tutor_tutors_in
, tutor_subject
LEFT JOIN tutor_tutor
on tutor_user.userid=tutor_tutor.userid
where tutor_user.userid=tutor_attends.userid
and tutor_attends.schoolid=80
and tutor_tutors_in.userid=tutor_user.userid
and tutor_tutors_in.subjectid=tutor_subject.subjectID
and tutor_subject.name='Aerospace Studies'
LIMIT 0, 15
感謝大家的所有答案;使用連接作爲'where'語句不是我以前想過的。考慮到我的培訓是在一所州立大學進行的,那裏有很多老師自己都「過時」了,所以我不會使我感到意外。 (其中一個仍然使用高架投影儀...即使有電腦投影儀可用) – RonLugge