我有三个表:Order
,Payment
和User
。
我正在尝试查找仅使用特定付款方式(现金)并且未使用任何其他付款方式的用户。
我构建的简单查询如下所示:
select
user.id,
user.fname,
user.lname,
user.email
from `order` as o
inner join payments on o.id = payments.order_id
inner join user on o.user_id = user.id
where o.orderplaced_ts > "2016-08-01 00:00:00"
and o.store_id = 6
and o.order_status != "Cancelled"
and payments.payment_method = "Cash"
group by user.id
但是,如果他们在时间范围内至少使用一次现金作为付款方式,则会返回用户。我如何限制现金和其他形式的付款?
我是否应该为每种付款方式设置多个子查询,然后将每次退货与其他付款进行比较以消除越来越多的用户?
答案 0 :(得分:0)
您可以添加条件,以便检查来自具有现金以外的付款方式的相同用户的付款以排除它们。 有点像: -
GaussianKernel
答案 1 :(得分:0)
您可以使用not in user.id使用其他方法
select
user.id,
user.fname,
user.lname,
user.email
from `order` as o
inner join payments on o.id = payments.order_id
inner join user on o.user_id = user.id
where o.orderplaced_ts > "2016-08-01 00:00:00"
and o.store_id = 6
and o.order_status != "Cancelled"
and payments.payment_method = "Cash"
and user.id not in (select distinct o.user_id
from `order`
inner join payments on o.id = payments.order_id
where payments.payment_method <> "Cash" )
group by user.id
答案 2 :(得分:0)
我会使用not exists子查询来排除在该时间范围内使用任何其他付款方式的用户:
select
user.id,
user.fname,
user.lname,
user.email
from `order` as o
inner join payments on o.id = payments.order_id
inner join user on o.user_id = user.id
where o.orderplaced_ts > "2016-08-01 00:00:00"
and o.store_id = 6
and o.order_status != "Cancelled"
and payments.payment_method = "Cash"
and not exists (select 1
from `order` as o2
inner join payments p2 on o2.id = p2.order_id
where o2.orderplaced_ts > "2016-08-01 00:00:00"
and o2.store_id = 6
and o2.order_status != "Cancelled"
and p2.payment_method != "Cash"
and o2.user_id=user.id)
group by user.id, user.fname, user.lname,user.email
不存在子查询的优点是它不必从子查询中提取结果,它只是检查子查询是否会返回任何记录。