1

提前为一个模棱两可的标题道歉,但我想不出一个好的标题。

我有 2 张桌子:

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

在费用表中,必须输入 booking_id 或 customer_id。不是都。

我正在尝试获取与customer_id关联的金额

因为customer_id有时在charges表中为null,所以我必须使用booking_id通过bookings表获取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)

但是,它似乎创建了一个无限循环。

有什么建议么?

谢谢,

4

3 回答 3

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)
于 2013-07-18T11:16:13.117 回答
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
于 2013-07-18T11:17:09.483 回答
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
于 2013-07-18T11:17:37.947 回答