[英]MySQL - Checking nonexistent records
I'm currently trying to check for existing rows in mysql.我目前正在尝试检查 mysql 中的现有行。
I have a table called "history", in this table I save records of movements in my platform.我有一个叫做“历史”的表,在这个表中我保存了我平台中的运动记录。
------------------------------------------------------------
| movement_id | movement | product_id |
------------------------------------------------------------
| 1 | movement_1 | 5 |
------------------------------------------------------------
| 2 | movement_2 | 5 |
------------------------------------------------------------
| 3 | movement_3 | 5 |
------------------------------------------------------------
| 4 | movement_1 | 6 |
------------------------------------------------------------
| 5 | movement_3 | 6 |
------------------------------------------------------------
I would like to get all the product_id
's that don't have movement_2
but does have movement_3
.我想获得所有没有movement_2
但确实有movement_3
的product_id
。 In the example above the ID that I would like to return is 6
, but this can be more than one id.在上面的示例中,我要返回的 ID 是6
,但这可以是多个 id。
Any help is greatly appreciated: :)任何帮助是极大的赞赏: :)
You can group by product_id
and use a condition in the having
clause:您可以group by product_id
并在having
子句中使用条件:
select product_id
from history
where movement in ('movement_2', 'movement_3')
group by product_id
having
sum(movement = 'movement_2') = 0
and
sum(movement = 'movement_3') > 0
or in this case only (because movement_2 < movement_3
), this would work also:或者仅在这种情况下(因为movement_2 < movement_3
),这也可以:
having min(movement) = 'movement_3'
See the demo .请参阅演示。
Results:结果:
> | product_id |
> | ---------: |
> | 6 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.