Answer the question
In order to leave comments, you need to log in
How to make a query to a table with a subquery for the same table with a field filter?
Good afternoon, it is difficult to formulate a request, I will try to describe in more detail
There is a table:
id; name; placement
5 ; element01 ; placement01
4 ; element02 ; placement01
3 ; element03 ; placement01
2 ; element01 ; placement02
1 ; element02 ; placement03
At the output, you need to get
id ; name; new_placement; old_placement
5 ; element01 ; placement01 ; placement02
4 ; element02 ; placement01 ; placement03
3 ; element03 ; placement01 ;
2; element01 ; placement01 ;
one ; element02 ; placement03 ;
Those. as if the history of the movement, in the context of each entry, where now and where it was, sorted by id
Wrote something similar, but the feeling that this is an expensive option and suboptimal
SELECT new_t.id, new_t.name, new_t.placement AS new_placement,
(SELECT old_t.placement
FROM table old_t
WHERE old_t.name = new_t.name AND
old_t.id < new_t.id
ORDER BY old_t.id DESC
LIMIT 1) AS old_placement
FROM table new_t
ORDER BY new_t.id DESC
Answer the question
In order to leave comments, you need to log in
according to your mind, the table structure should be formed immediately in the second form, + change datetime, because sorting by id is not the best option, there may be nuances, this field is not intended for this.
also see this answer or google sql nested sets.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question