简体   繁体   中英

Selecting the next occurence of a certain record in MySQL

I'm building a reporting module for a client, and their current process makes it quite difficult to do what I'm trying to do. Database is MySQL, module is written in PHP.

Essentially, I need to find an order that is processing between the requested dates. Simple enough. Then, I need to find the first time its status is set to shipping, because it could be set back and forth between processing and shipping multiple times, if the order is returned or warrantied, etc.

But, I need this to be done in two separate queries.

I can get the Order ID's where they are processing. My problem is with the second query, where I'm doing:

SELECT * FROM status_history WHERE orders_id IN {list_of_ids} AND status = 'shipped' GROUP BY orders_id .

My problem is that the 'shipped' status row that this query produces may be before/after the required one.

I understand that the main problem is with their process, and the legacy system I have to work with, but that I can't change.

What I need to do is: SELECT * FROM status_history WHERE orders_id IN <list_of_ids> AND status = 'shipped' AND date_added > {date at processing} AND date_added < {date at next occurrence of processing, if there is one} GROUP BY orders_id

Don't use SELECT * with GROUP BY . It is a sign of bad querying and unclear thinking. Where do the values for all the columns come from -- the ones that are not in the GROUP BY clause?

If you want the date of the first shipment, then you can get that date:

SELECT sh.orders_id, MIN(date_aded) as FirstShippedDate
FROM status_history sh
WHERE sh.orders_id IN <list_of_ids> AND sh.status = 'shipped' AND
      sh.date_added > {date at processing} AND
      sh.date_added < {date at next occurrence of processing, if there is one} 
GROUP BY orders_id;

Note: You probably do not need two queries. You should be able to use a subquery to generate the list and use it in this query.

And, if you need the complete record, then join this result set back to the original table.

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.

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