连接和相关子查询

时间:2017-05-28 10:50:57

标签: php mysql sql laravel eloquent

无法找出我想要仅显示未经验证的订单但不包含已经拥有至少一个已验证订单的客户的情况的查询。一个客户可以在DB中拥有更多记录,因为对于每个订单,客户表中的新记录也是如此,因此跟踪特定用户的唯一方法是按customer_number。

我的数据库结构(简化):

customers:
id | customer_number

orders:
id | customer_id | isVerified

我可能需要结合连接和相关查询(在customers表中搜索每个customer_number的记录,并检查isVerified列是否为false),这最终可能非常慢,特别是对于数千条记录。

我使用Laravel,如果这可以使事情变得更容易,那么可以使用Eloquent ORM。

(第二个想法:或者,重写该部分以便为特定用户的订单创建一个用户记录会更快更有效。)

有什么想法吗?谢谢

4 个答案:

答案 0 :(得分:1)

可能有几种方法可以做到这一点,但你可以通过连接,聚合和条件求和来实现这个结果:

select  a.customer_id,
        sum( case when isVerified = 1 then 1 else 0 end ) as Num_Verified,
        sum( case when isVerified = 0 then 1 else 0 end ) as Num_unVerified
from    customers as a
        left join
        orders as b
        on a.customer_id = b.customer_id
group by a.customer_id
having  Num_Verified = 0
        and Num_unVerified > 0

SQLfiddle here

答案 1 :(得分:1)

你可以这样做:

$customer_id = Customer::join('orders','customers.id','orders.cutomer_id')
             ->where('isVerified',true)
             ->select('orders.*')
             ->groupBy('customer_id')
             ->pluck('customer_id');

这将为客户提供至少一个经过验证的订单。

现在让客户获得未经验证的订单:

$customers = Customer::join('orders','customers.id','orders.customer_id')
             ->where('isVerified',false)
             ->whereNotIn('customer_id',$customer_id)
             ->select('customers.customer_number','orders.*')
             ->groupBy('customer_id')
             ->pluck('customer_id');

答案 2 :(得分:0)

这个怎么样?

$customer_list = customers::where('customer_number',$customer_number)->with('orders',function($query){
$query->where('isVerified',0);
})->get();

答案 3 :(得分:0)

一种方法是聚合查询:

select c.customer_number
from customers c join
     orders o
     on c.customer_id = o.customer_id
group by c.customer_number
having sum(isVerified = 1) = 0 and
       sum(isVerified = 0) > 0;

此结构假定isVerified是一个数字,其值为0表示false,1表示true。