Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
涉及多个表和OR语句的Mysql查询_Mysql_Sql - Fatal编程技术网

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

涉及多个表和OR语句的Mysql查询,mysql,sql,Mysql,Sql,很抱歉,前面的标题模棱两可,但我想不出一个好标题 我有两张桌子: bookings(booking_id, customer_id) charges(customer_id, booking_id, amount) 在费用表中,必须输入预订id或客户id。不是两者都有 我正在尝试获取与客户id相关的金额 由于费用表中的客户id有时为空,因此我必须使用booking id通过bookings表获取客户id 所以,我有一个这样的问题: SELECT c.amount FROM charges as

很抱歉,前面的标题模棱两可,但我想不出一个好标题

我有两张桌子:

bookings(booking_id, customer_id)
charges(customer_id, booking_id, amount)
在费用表中,必须输入预订id或客户id。不是两者都有

我正在尝试获取与客户id相关的金额

由于费用表中的客户id有时为空,因此我必须使用booking id通过bookings表获取客户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)
然而,它似乎创建了一个无限循环

有什么建议吗


谢谢,

问题在于,根据
where
子句的结构,您正在进行
交叉联接(笛卡尔积)

更好的方法是使用
左外连接
(以及正确的连接语法)。因此,如果存在
bookings
表,请加入该表。然后在
where
子句中使用
在以下任一位置查找
客户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)

为什么不使用连接?像

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