Due to changing requirements I've revisited an interface I created a couple of months ago. More features, more data. I received help with the tricky ordering requirements of the data over here. But requirements have changed, or to be more accurate, expanded. I've been tinkering for several hours now and have had no success. I'm hoping SO might be able to help unstick me once again.
Here is some simplified sample data as it appears in the database, and how I need to order it.
**RAW** **DESIRED** ╔════╦════════╦═══════════╦═══════════╗ ╔════╦════════╦═══════════╦═══════════╗ ║ id ║ job_id ║ action_id ║ iteration ║ ║ id ║ job_id ║ action_id ║ iteration ║ ╠════╬════════╬═══════════╬═══════════╣ ╠════╬════════╬═══════════╬═══════════╣ ║ 1 ║ 1 ║ 1 ║ 0 ║ ║ 14 ║ 6 ║ 1 ║ 0 ║ ║ 2 ║ 1 ║ 2 ║ 0 ║ ║ 16 ║ 6 ║ 2 ║ 0 ║ ║ 3 ║ 2 ║ 1 ║ 0 ║ ║ 12 ║ 1 ║ 1 ║ 1 ║ ║ 4 ║ 3 ║ 1 ║ 0 ║ ║ 13 ║ 1 ║ 2 ║ 1 ║ ║ 5 ║ 4 ║ 1 ║ 0 ║ ║ 15 ║ 1 ║ 3 ║ 1 ║ ║ 6 ║ 3 ║ 2 ║ 0 ║ ║ 8 ║ 5 ║ 1 ║ 0 ║ ║ 7 ║ 3 ║ 3 ║ 0 ║ ║ 10 ║ 5 ║ 2 ║ 0 ║ ║ 8 ║ 5 ║ 1 ║ 0 ║ ║ 11 ║ 5 ║ 3 ║ 0 ║ ║ 9 ║ 4 ║ 2 ║ 0 ║ ║ 5 ║ 4 ║ 1 ║ 0 ║ ║ 10 ║ 5 ║ 2 ║ 0 ║ ║ 9 ║ 4 ║ 2 ║ 0 ║ ║ 11 ║ 5 ║ 3 ║ 0 ║ ║ 4 ║ 3 ║ 1 ║ 0 ║ ║ 12 ║ 1 ║ 1 ║ 1 ║ ║ 6 ║ 3 ║ 2 ║ 0 ║ ║ 13 ║ 1 ║ 2 ║ 1 ║ ║ 7 ║ 3 ║ 3 ║ 0 ║ ║ 14 ║ 6 ║ 1 ║ 0 ║ ║ 3 ║ 2 ║ 1 ║ 0 ║ ║ 15 ║ 1 ║ 3 ║ 1 ║ ║ 1 ║ 1 ║ 1 ║ 0 ║ ║ 16 ║ 6 ║ 2 ║ 0 ║ ║ 2 ║ 1 ║ 2 ║ 0 ║ ╚════╩════════╩═══════════╩═══════════╝ ╚════╩════════╩═══════════╩═══════════╝
**EXPLAINED** ╔════╦════════╦═══════════╦═══════════╗ ║ id ║ job_id ║ action_id ║ iteration ║ ╠════╬════════╬═══════════╬═══════════╣ ORDERED BY: ║ 14 ║ 6 ║ 1 ║ 0 ║ ║ 16 ║ 6 ║ 2 ║ 0 ║ The largest id with action_id of 1 ╠════╬════════╬═══════════╬═══════════╣ followed by all of the rows with the ║ 12 ║ 1 ║ 1 ║ 1 ║ same job_id and iteration number as ║ 13 ║ 1 ║ 2 ║ 1 ║ the first, ordered by ascending ║ 15 ║ 1 ║ 3 ║ 1 ║ action_id. ╠════╬════════╬═══════════╬═══════════╣ ║ 8 ║ 5 ║ 1 ║ 0 ║ Then the next largest id with ║ 10 ║ 5 ║ 2 ║ 0 ║ action_id = 1, etc. ║ 11 ║ 5 ║ 3 ║ 0 ║ ╠════╬════════╬═══════════╬═══════════╣ ║ 5 ║ 4 ║ 1 ║ 0 ║ ║ 9 ║ 4 ║ 2 ║ 0 ║ ╠════╬════════╬═══════════╬═══════════╣ ║ 4 ║ 3 ║ 1 ║ 0 ║ ║ 6 ║ 3 ║ 2 ║ 0 ║ ║ 7 ║ 3 ║ 3 ║ 0 ║ ╠════╬════════╬═══════════╬═══════════╣ ║ 3 ║ 2 ║ 1 ║ 0 ║ ╠════╬════════╬═══════════╬═══════════╣ ║ 1 ║ 1 ║ 1 ║ 0 ║ ║ 2 ║ 1 ║ 2 ║ 0 ║ ╚════╩════════╩═══════════╩═══════════╝
I'm currently using an ORDER BY
like this:
SELECT *
FROM reports as r
ORDER BY
FIND_IN_SET(r.job_id, ( SELECT GROUP_CONCAT(job_id ORDER BY id DESC)
FROM reports
WHERE action_id = 1)),
r.action_id
But it doesen't take into account the iteration. I can't see where I can fit that bit of logic in. Can anybody offer any assistance?
Many thanks!