mysql - Sorting by IP then keep selecting records until I have 3 unique IPs -


i'm totally thinking harder have.

i have report table in database has ip-column (varchar), data-column (int) , timestamp-column (timestamp).

i have write query sort timestamp desc, keep selecting records top until resultset contains @ least 3 unique ip's, in order of occurrence until 4th ip encountered.

for example:

ip         data         timestamp 1.1.1.0    0            1-1-2016 1.1.1.1    1            1-2-2016 1.1.1.1    2            1-3-2016 1.1.1.2    1            1-4-2016 1.1.1.3    1            1-5-2016 1.1.1.3    1            1-6-2016 

in case want result set of:

ip         data         timestamp 1.1.1.3    1            1-6-2016 1.1.1.3    1            1-5-2016 1.1.1.2    1            1-4-2016 1.1.1.1    2            1-3-2016 1.1.1.1    1            1-2-2016 

just use-case: backend using data group ips, generate average of data-column (basically flattening 1+ ip's 1), before processed further.

i tried messing group by, having, sub-query, can't figure out while seems trivial!

edit: information

select distinct ip report order timestamp desc limit 3 

does not respect first occurrence of ip. example if 1.1.1.3 in table last , fourth occurrence, distinct put ip should on top order-wise fourth (meaning excluded limit 3).

i tried:

select * report ip in (     select distinct ip     report     order timestamp desc ) order timestamp desc limit 3 

and seems work, highly unoptimized... limit not work in in, mysql rejects that. , when use limit problem outlined happen.

something following query should work if understand question correctly:

select *  report timestamp >= (     select min(timestamp) (         select ip, min(timestamp) timestamp         report         group ip         order timestamp desc         limit 3     ) x ) order timestamp desc 

there may ways optimise query, not know if required in scenario.

see this sql fiddle test in practice.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -