2015-09-02 112 views
0

我試圖讓下面的SQL工作:MYSQL:選擇/和/或兩個表

SELECT * FROM tc_appointment as tcAppointment, tc_message as tcMessage 
WHERE tcAppointment.counsellor_id = 502 
AND 
(
    (tcAppointment.tc_message_id = tcMessage.id AND tcMessage.marked_read = false AND tcMessage.sender_id != 502) 
    OR 
    (tcAppointment.cancelled = true AND tcAppointment.cancelled_acknowledged = false) 
    OR 
    (tcAppointment.confirmed = false) 
); 

tcAppointment.tc_message_id是在表中唯一tc_appointment進入空。我試圖讓它返回爲counsellor_id = 502和第二OR statment是true

我似乎被卡住,因爲tc_message as tcMessage子句和第一AND/OR聲明的,但我不知道爲什麼。任何人都可以指出我正確的方向嗎?

+2

瞭解ANSI 92使用INNER,LEFT聯接和右聯接語法。 http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/或者學習使用ANSI 92加入之前的外連接的概念。我相信符號是'* ='或'= *',或者它是'+ ='和'= +'......我不記得了。 – xQbert

回答

1

試着加入2個表,並使用 '去哪兒':

SELECT * FROM tc_appointment as tcAppointment 
    LEFT JOIN tc_message as tcMessage 
    ON 
    ((tcAppointment.tc_message_id = tcMessage.id AND tcMessage.marked_read = false AND tcMessage.sender_id != 502) 
    OR 
     (tcAppointment.cancelled = true AND tcAppointment.cancelled_acknowledged = false) 
     OR 
     (tcAppointment.confirmed = false) 
) 

    WHERE tcAppointment.counsellor_id = 502