我下面有两个相似的表
如果我们的购物车表如下,
id date title
---------------------
1 2016 a
2 2015 b
3 2018 c
4 2019 dd
产品表如下所示
id cart_id status
--------------------------
1 2 paid
2 2 paid
3 1 paid
4 1 unpaid
5 1 paid
6 3 paid
7 3 paid
预期输出(仅支付了所有产品的购物车)为
cart_id status
-------------------
3 paid
2 paid
答案 0 :(得分:0)
尝试使用此调整后的代码-
SELECT carts.id,'Paid' Status
FROM carts
INNER JOIN product on carts.id = product.cart_id
GROUP BY carts.id
HAVING COUNT(Status) = SUM(CASE WHEN status = 'Paid' THEN 1 ELSE 0 END)
答案 1 :(得分:0)
这似乎是最简单的逻辑:
select p.cart_id, p.status
from product p
where p.status = 'paid';
答案 2 :(得分:0)
您可以group by cart_id
并使用HAVING
子句,条件是'unpaid'
列中没有status
值:
select cart_id, max(status) status
from product
group by cart_id
having sum(status = 'unpaid') = 0
我假设在列status
中唯一可能的值是'paid'
和'unpaid'
,因此您可以使用max(status) status
作为第二个值,而不是'paid' status
专栏。
或不存在:
select distinct p.cart_id, p.status
from product p
where not exists (
select 1 from product
where cart_id = p.cart_id and status = 'unpaid'
)
请参见demo。
结果:
| cart_id | status |
| ------- | ------ |
| 2 | paid |
| 3 | paid |