We are using php/postgresql for process control at our company. The company is repairing units, and the repair process is followed by the process control system.
The unit table stores the information about the individual units.
- unit.id : the id of the unit
- unit.sn : the serial number of the unit
The unit_process table stores every process step the unit went through in it's lifetime.
- unit_process.id : the id of the process step
- unit_process.unit_id : the id of the unit
- unit_process.process_id : the id of the process.
(the real tables have more columns)
an sql to find a unit's process steps in chronological order:
SELECT process_id
FROM unit
INNER JOIN unit_process on unit.id=unit_process.unit_id
ORDER BY unit_process.id
I would like to create a query which finds all process steps which are happened before process steps that have a specific process_id
So I have a process_id, I need to find all unit_process rows that happened just before a process which has that process_id
Currently I am using about the worst method I can imagine.
For example let's say, I need all previous process steps which happened before processes that has process_id=17
First, I list the units which have processes with process_id=17
SELECT unit.id
FROM unit
INNER JOIN unit_process on unit.id=unit_process.unit_id
WHERE process_id=17
Then I store them in a php array.
Secondly, I use a php foreach which contains the following query for every unit id I got from the previous query.
SELECT id,process_id
FROM unit_process
WHERE unit_id=$unit_id
ORDER BY id
After this, I could easily find out using php what process was before the process_id=17 process step, since I just have to find the biggest id value which is still lower than the (process_id=17)'s.
It could use up to thousands of querys in that foreach, and I want to change that, but I don't have enough SQL knowledge to do it on my own.
Is it possible to do this in a single query?
Sample input greens are needed, yellows are the process_id=17 units. Notice that there is a process_id=17 wich is also needed :
Sample output:
I hope I didn't messed up the samples, I just came up with these for example.