Finding newest or flagged row in a one to many relationship in MySQL -


sorry if title poor, i'm trying join primary table related table , return single row matches flagged or recent row in related table.

primary table, let's call group, has columns:

id, name 

related table, let's call user, has columns:

id, group_id, email, default, updated_datetime 

the query should return single 'group', , either matching record 'user' default=1 (preferred), or if no rows have default=1 row max(updated_datettime). 'user' have 1-n rows group.id = user.group_id.

example result:

group.id, group.name, user.email, user.default, user.updated_datetime 1, 'test', 'email', '0', '2015-06-10 12:00' 2, 'other', 'email', 1', '2015-06-08 10:00' 

both tables contain lot of data i'd prefer join's , not subqueries. know how subqueries i'm having trouble doing joins since grouping has multiple conditions.

i'm fine doing aliases, eg:

select a.* (query) 

i'm trying avoid subqueries in main select, eg:

select group.id, group.name, (query) user.id 

thanks!

first, need use 2 joins , if() in select select default user or last updated user. then, because want join using max() condition, need subqueries.

something should on right track:

select group.id, if(default_user.id not null, default_user.id, last_updated_user.id) user_id group left join user default_user on default_user.group_id = group.id , default_user.default = 1 join (   select user.* (     select group_id, max(updated_datetime) updated_datetime user group group_id   ) max_per_group join user using(group_id, updated_datetime) ) last_updated_user on last_updated_user.group_id = group.id 

but note isn't fast query, , if need frequently, might want refactor tables. example, add foreign keys default_user_id , last_updated_user_id in group table.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -