根据订单ID获取所有客户付款

时间:2017-12-26 17:05:16

标签: php mysql laravel-5.3

我想知道有人可以帮我解决这个复杂的mysql查询。

我有3张桌子:

表#1:Customer_Order有两列customer_idorder_id
 表#2:Order_Payment也有order_id
 表#3:Orders,其id是订单ID。

如果可以根据order_id检索特定客户的所有付款,我就会徘徊。我只有一个order_id,但我没有customer_id并且基于order_id,我应该能够检索所有付款,甚至还有那些尚未付款的付款

我就是这样做的:

我首先检索已知的订单

select * from customer_order where order_id = 1351

然后我尝试根据返回的内容构建查询

select * from (
    select * from customer_order where order_id = 1351
) c1
left join 
    (select op.order_id, customer_id from order_payment op inner join customer_order co on op.order_id = co.order_id
    ) c2 on c1.customer_id = c2.customer_id

我也试试

select customer_id from (
    select customer_id from `order_payment` inner join `customer_order` on `customer_order`.`order_id` = `order_payment`.`order_id` 
    where order_payment.order_id=1351
    order by `created_at` asc) as s
inner join customers on s.customer_id = customers.id

但我只收到一笔订单付款,而不是那些尚未付款的订单。

如果有人帮我解决问题,我将不胜感激。

3 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

SELECT 
    co.*,
    op.*
FROM
    customer_order AS co
    LEFT JOIN order_payment AS op ON op.order_id = co.order_id

WHERE
    co.customer_id IN 
    (
         SELECT customer_id FROM customer_orders WHERE order_id=1351
    )

答案 1 :(得分:0)

您可以与customer_order两次加入。一旦从给定的order_id转到customer_id,则第二次获得所有客户的订单。

select op.*
FROM order_payment AS op
JOIN customer_order AS co1 ON co1.order_id = op.order_id
JOIN customer_order AS co2 ON co2.customer_id = co1.customer_id
WHERE co2.order_id = 1351

我认为没有理由使用LEFT JOINorder_payment中的列应该是外键,因此始终会有匹配。

答案 2 :(得分:0)

我最终运行了2个查询。首先加载已完成特定订单付款的客户,然后为该客户加载未付订单。

感谢大家的帮助。