I'm currently trying to check for existing rows in 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
. In the example above the ID that I would like to return is 6
, but this can be more than one id.
Any help is greatly appreciated: :)
You can group by product_id
and use a condition in the having
clause:
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:
having min(movement) = 'movement_3'
See the demo .
Results:
> | product_id |
> | ---------: |
> | 6 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.