2013-07-18 98 views
1

對不起,一個模棱兩可的標題,但我想不出一個好的。涉及多個表和一個OR語句的Mysql查詢

我有2個表:

bookings(booking_id, customer_id) 
charges(customer_id, booking_id, amount) 

凡在收費表中,無論是booking_id或CUSTOMER_ID必須輸入。不是都。

我試圖讓與某個相關CUSTOMER_ID

因爲CUSTOMER_ID的有時是空的收費表,我必須使用booking_id通過預訂表,獲取CUSTOMER_ID。

所以,我有這樣的查詢:

SELECT c.amount 
FROM charges as c, bookings as b 
WHERE (c.customer_id = 1234) OR 
(c.customer_id = null AND c.booking_id = b.booking_id AND b.customer_id = 1234) 

然而,這似乎創造一個無限循環。

有什麼建議嗎?

感謝,

回答

3

的問題是,你正在做一個cross join(笛卡爾乘積),根據您的where條款的結構。

更好的方法是使用left outer join(以及正確的連接語法)。因此,如果存在,請加入bookings表。然後使用orwhere子句中尋找對customer_id比賽在兩個地方:

SELECT c.amount 
FROM charges as c left outer join 
    bookings as b 
    on c.booking_id = b.booking_id 
WHERE (c.customer_id = 1234) OR (b.customer_id = 1234) 
+0

1只是在[SQLFiddle]測試(http://sqlfiddle.com/#!9/b8458/6) – hims056

0

爲什麼你不使用JOIN?像

SELECT c.amout 
FROM charges AS c 
LEFT JOIN bookings AS b ON c.bookin_id = b.booking_id 
WHERE c.customer_id = 1234 OR b.customer_id = 1234 
0
SELECT amount, customer_id from charges where customer_id = 1234 
UNION 
select amount, b.customer_id from charges c, bookings b where b.booking_id = c.booking_id and c.customer_id is null and b.customer_id = 1234