1

我无法获得正确的数据。

我的表结构如下:

id     INT(11)    AI
order_id     INT(11)
status varchar(45)

此表记录订单的状态更改。所以 order_id 的状态很少。

现在我需要选择行并按 order_id 对它们进行分组,其中 order 从来没有状态(甚至没有给定 order_id 的状态)!= 'example'

我们不显示订单,其中一名成员的状态 = 示例

样本数据

1   12   ready
1   12   example
2   13   ready
2   13   sent

所以我根本不希望显示订单 12,因为其中一个成员具有“示例”状态

我已经尝试对结果进行分组,但这还不够。

4

5 回答 5

2

您可以这样尝试...它将返回所有从未有过状态的订单 id -example

Select 
       Order_id,
       from TableName A where Not Exists(
                                        Select id from TableName B where
                                                       status='example' and 
                                         a.Order_id=b.Order_id
                                        )
      group by Order_id
于 2013-07-08T11:23:56.793 回答
2

你可以通过简单的连接查询来做到这一点:

select a.order_id 
from ordrstatus as a left outer join (select orderid , count(*) as status  from orderstatus where status = 'example' group by orderid) as b on a.orderid = b.orderid
where b.status = 0 or b.status is NUll 

加入查询总是比 IN 查询运行得更快。通过在查询中使用加入,它将只运行一次。

于 2013-07-08T11:25:32.960 回答
1

不太确定您是否想要具有示例状态的订单记录,或者从未具有示例状态的订单记录

要获取具有示例状态的订单列表(状态分组):-

SELECT a.order_id, GROUP_CONCAT(a.status)
FROM SomeTable a
INNER JOIN 
(
    SELECT order_id, COUNT(*)
    FROM SomeTable
    WHERE status = 'example'
    GROUP BY order_id
) b
ON a.order_id = b.order_id
GROUP BY order_id

获得那些从未有过exmaple状态的人

SELECT a.order_id, GROUP_CONCAT(a.status)
FROM SomeTable a
LEFT OUTER JOIN 
(
    SELECT order_id, COUNT(*)
    FROM SomeTable
    WHERE status = 'example'
    GROUP BY order_id
) b
ON a.order_id = b.order_id
WHERE b.order_id IS NULL
GROUP BY order_id

编辑

SELECT a.order_id, GROUP_CONCAT(a.status)
FROM SomeTable a -- Statuses
LEFT OUTER JOIN 
(
    SELECT order_id, COUNT(*)
    FROM SomeTable
    WHERE status = 'example'
    GROUP BY order_id
) b -- Get any order id which has had a status of example (as a LEFT JOIN)
ON a.order_id = b.order_id
INNER JOIN
(
    SELECT order_id, MAX(id) AS Latestid
    FROM SomeTable
    GROUP BY order_id
) c -- Get the latest status for each order (ie, max id)
ON a.order_id = c.order_id
LEFT OUTER JOIN 
(
    SELECT order_id, id
    FROM SomeTable
    WHERE status = 'example2'
) d -- Get the id of the order status of example2
ON a.order_id = d.order_id AND c.Latestid = d.id -- join on the same order id and that the record id matches the latest record id
WHERE b.order_id IS NULL -- reject those where a match was found on example for any status
AND d.order_id IS NULL -- reject those where a match was found on example2 for the latest status
GROUP BY order_id
于 2013-07-08T12:00:19.060 回答
0

尝试这个

SELECT Order_ID FROM tbl_Orders
WHERE Status NOT IN ('example')
GROUP BY Order_ID
于 2013-07-08T11:25:18.680 回答
0
SELECT DISTINCT x.order_id
           FROM  order_status x
           LEFT
           JOIN order_status y
             ON y.order_id = x.order_id
            AND y.status = 'example'
          WHERE y.id IS NULL;
于 2013-07-08T12:00:15.217 回答