[英]Mysql query involving multiple tables and an OR statement
Sorry in advance for an ambiguous title, but I can't think of a good one. 提前抱歉有一个模糊的标题,但我想不出一个好的。
I have 2 tables: 我有2张桌子:
bookings(booking_id, customer_id)
charges(customer_id, booking_id, amount)
where in charges table, either booking_id or customer_id must be entered. 在费用表中,必须输入booking_id或customer_id。 Not both.
不是都。
I'm trying to get amount that are associated with a customer_id 我正在尝试获取与customer_id相关联的金额
Because the customer_id's are null sometimes in charges table, I have to use booking_id to acquire customer_id through bookings table. 因为customer_id有时在费用表中为空,所以我必须使用booking_id通过预订表获取customer_id。
So, I had a query like this: 所以,我有这样的查询:
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)
However, it seems to create an infinite loop. 但是,它似乎创造了一个无限循环。
Any suggestions? 有什么建议么?
Thanks, 谢谢,
The problem is that you are doing a cross join
(cartesian product), based on the structure of your where
clause. 问题是你正在根据
where
子句的结构进行cross join
(笛卡尔积)。
A better approach is to use left outer join
(and proper join syntax). 更好的方法是使用
left outer join
(和正确的连接语法)。 So, join to the bookings
table, if it exists. 因此,如果存在,请加入
bookings
表。 Then use or
in the where
clause to look for a match on the customer_id
in either place: 然后在
where
子句中使用or
在两个地方的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)
Why you don't use a JOIN ? 为什么不使用JOIN? like
喜欢
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.