简体   繁体   English

满足特定条件的 MySQL Select 行

[英]MySQL Select rows that meet specific condition

I have table orders that does look like this:我有看起来像这样的表orders

order_id | item_id | quantity
     1        1         2
     1        2         5
     2        3         13
     2        4         5
     3        3         1

I do want to SELECT all rows, but I'd like to skip entire orders that does contain exactly 13 items of item_id 3. In this example it should skip rows with order_id=2.我确实想要 SELECT 所有行,但我想跳过确实包含 13 项 item_id 3 的整个订单。在这个例子中,它应该跳过 order_id=2 的行。 Is it possible to do with one simple query?是否可以使用一个简单的查询?

You can use a NOT EXISTS clause to find any orders that don't have 13 items of item_id 3:您可以使用NOT EXISTS子句来查找没有 13 个item_id 3 的订单:

SELECT *
FROM orders o1
WHERE NOT EXISTS (SELECT * 
                  FROM orders o2
                  WHERE o2.order_id = o1.order_id
                    AND o2.item_id = 3 
                    AND o2.quantity = 13)

Output: Output:

order_id    item_id     quantity
1           1           2
1           2           5
3           3           1

Demo on dbfiddle dbfiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM