如何跨组及其内容过滤表

时间:2017-05-29 07:38:44

标签: mysql sql select filter

在我的表中,必须生成物品的订单(在我的例子中简化)。 我只需要过滤那些完全完成的订单。如果所有订单的状态(具有相同的order_id)为' 4'则订单已完成。或' -1'。

"id"    "order_id"  "item_nr"   "status"
"689"   "4"         "M2223"     "3"
"690"   "4"         "K3224"     "-1"
"691"   "4"         "X1837"     "4"
"692"   "4"         "M2338"     "0"
"693"   "5"         "E7273"     "4"
"694"   "5"         "E8883"     "-1"
"695"   "5"         "B9217"     "4"
"696"   "5"         "B2662"     "4"

在示例中:我想得到结果:

"693"   "5"         "E7273"     "4"
"694"   "5"         "E8883"     "-1"
"695"   "5"         "B9217"     "4"
"696"   "5"         "B2662"     "4"

如何选择这个?

1 个答案:

答案 0 :(得分:3)

一个选项是将LEFT JOIN您的表格添加到子查询中,该子查询标识所有匹配订单,然后仅保留来自不匹配订单的记录。这意味着那些匹配订单没有任何状态不完整的记录。

SELECT t1.*
FROM yourTable t1
LEFT JOIN
(
    SELECT order_id
    FROM yourTable
    WHERE status NOT IN ('4', '-1')
) t2
    ON t1.order_id = t2.order_id
WHERE t2.order_id IS NULL

<强>输出:

enter image description here

在这里演示:

Rextester

根据@shadow的评论,我们也可以使用NOT EXISTS

来表达此查询
SELECT t1.*
FROM yourTable t1
WHERE NOT EXISTS
(
    SELECT 1
    FROM yourTable t2
    WHERE t2.status NOT IN ('4', '-1') AND t2.order_id = t1.order_id
)