我无法获得正确的数据。
我的表结构如下:
id INT(11) AI
order_id INT(11)
status varchar(45)
此表日志状态随订单而变化。 所以order_id的状态很少。
现在我需要选择行并按order_id对它们进行分组,其中order永远不会有状态(甚至没有给定order_id的状态)!='example'
我们不显示订单,其中一个成员有status = example
示例数据
1 12 ready
1 12 example
2 13 ready
2 13 sent
所以我不希望订单12显示,因为其中一个成员具有“示例”状态
我尝试过分组结果,但这还不够。
答案 0 :(得分: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查询运行得更快。通过在查询中使用Join,它只会运行一次。
答案 1 :(得分:1)
您可以尝试这样...它将返回所有从未拥有状态的订单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
答案 2 :(得分: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
答案 3 :(得分:0)
试试这个
SELECT Order_ID FROM tbl_Orders
WHERE Status NOT IN ('example')
GROUP BY Order_ID
答案 4 :(得分: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;