I
I
imater2013-01-25 12:25:11
MySQL
imater, 2013-01-25 12:25:11

Help to make a query on MySQL. Search in the second table - whether this record has already been synchronized for this user

There are 2 tables:
tree:
1. id - autoincrement index
2. changetime - stores the last synchronization time

tree_sync:
1. id - link to the id of the first table.
2. changetime — record change time at the moment of user synchronization
3. user_id — unique user ID

Task:
It is necessary to display all elements of the tree table whose tree.changetime is not equal to the maximum change time in the tree_sync.changetime table for a particular user. + add all tree elements that are not in the second table.

Example:
tree:
id: 4552 changetime:13:10
id: 4553 changetime:12:40
id: 4554 changetime:12:35
id: 4555 changetime:12:37

tree_sync:
id: 4552 user_id: x1 changetime: 11:40
id: 4552 user_id: x1 changetime: 11:45
id: 4552 user_id: x1 changetime: 11:55
id: 4552 user_id: x2 changetime: 12:30
id: 4552 user_id: x2 changetime: 13:10 Output:

id
: 4552; changetime: 13:10 for user x1
and don't display 4552 for user x2 because he has already synced.

PS: The task in words: you need to display all the id from the first table that have not yet been synchronized for this user. The second table records each synchronization of any users. The fact that the record has changed can be seen from the changetime in the first table. If user x1 has synced, then tree_sync will have an entry with tree.changetime = tree_sync.changetime. How to display all this in one query in mySQL?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivnik, 2013-01-25
@imater

select t.* from tree t left outer join (select id, max(changetime) changetime from tree_sync where user_id=2 group by id) ts on (t.id=ts.id) where ts.changetime is null or ts.changetime < t.changetime

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question