我有这种表(简化):
640
并希望选择所有订单,其中每个orders sample data below
---------------------------------------------
id INT: 1 2 3 4 5
userid INT 10 10 10 20 20
status CHAR(1) A A B A C
状态为userid
,但根本没有订单IN ('A','B')
。
因此,上述数据的输出会产生ID = 1,2和3 的订单。用户ID = 10有订单A和B,但没有C或D.
换句话说:为订单状态为A或B但没有状态C或D的客户选择订单。
我从这开始:
IN ('C','D')
但是认为SELECT
xcart_orders.orderid,
xcart_orders.*
FROM xcart_orders
JOIN (
select count(*) as bad_statuses, userid from xcart_orders
where status in ('C','D')
group by userid
) bo
ON bo.userid=xcart_orders.userid
JOIN (
select count(*) as good_statuses, userid from xcart_orders
where status in ('A','B')
group by userid
) bo2
ON bo2.userid=xcart_orders.userid
WHERE bo2.good_statuses>0 and bo.bad_statuses=0
对于'坏'状态不会返回零,所以我没有得到任何结果。
答案 0 :(得分:1)
您的汇总没有GROUP BY
,要检查结果,您需要我们HAVING
而不是WHERE
SELECT
xcart_orders.orderid,
xcart_orders.*,
SUM(CASE WHEN xcart_orders.status in ('C','D') THEN 1 ELSE 0 END) AS bad_statuses,
SUM(CASE WHEN xcart_orders.status in ('A','B') THEN 1 ELSE 0 END) AS good_statuses
FROM xcart_orders
GROUP BY orderid
HAVING bad_statuses = 0
AND good_statuses > 0
请注意,如果您需要首先订购的特定字段,那么您从xcart_orders.*
获得的字段将是随机的(或非确定性字段)。
首先,您要对GROUP BY user_id
进行检查,以确定其状态是否与'A', 'B'
不同
然后您从user_id
:
SELECT `user_id`
FROM orders1
GROUP BY `user_id`
HAVING COUNT(*) = COUNT(CASE WHEN `status` IN ('A', 'B') THEN 1 END);
SELECT *
FROM orders1
WHERE `user_id` IN (SELECT `user_id`
FROM orders1
GROUP BY `user_id`
HAVING COUNT(*) = COUNT(CASE WHEN `status` IN ('A', 'B') THEN 1 END)
);
输出