Mysql查询涉及多个表和一个OR语句

时间:2013-07-18 11:10:50

标签: mysql sql

提前抱歉标题含糊不清,但我觉得不错。

我有两张桌子:

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 个答案:

答案 0 :(得分:3)

问题在于,您正在根据cross join子句的结构执行where(笛卡尔积)。

更好的方法是使用left outer join(以及正确的连接语法)。因此,如果存在,请加入bookings表。然后使用or子句中的where在两个地方的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)

答案 1 :(得分: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

答案 2 :(得分: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