sql - How to retrieve the last id value before i "count" a column in mysql? -


when select values of 2 tables

select     tab.id    ,tab.name    ,tab2.id    ,tab2.name    ,count(distinct tab3.id) totalusers master tab   left join user tab2 on tab.id = tab2.cod   left join user tab3 on tab.id = tab3.cod tab.id = 5 limit 1 order tab2.id desc 

or

select     tab.id    ,tab.name    ,tab2.id    ,tab2.name    ,count(tab2.id) master tab   left join user tab2 on tab.id = tab2.cod tab.id = 5 limit 1 order tab2.id desc 

i got

+ ------ + -------- + ------- + --------- + ------------------ +  | tab.id | tab.name | tab2.id | tab2.name | count(tab3.id)     | + ------ + -------- + ------- + --------- + ------------------ +  | 5      | home1    | 132     | joao      | 3                  | + ------ + -------- + ------- + --------- + ------------------ +  

but tab2.id retrieve first value of table, order doesn't works when count value, how last key 134 , name ?

users

+ ---- + ----- + --- + | id   | name  | cod | + ---- + ----- + --- + | 132  | joao  |  5  | + ---- + ----- + --- + | 133  |  |  5  | + ---- + ----- + --- + | 134  | cindy |  5  | + ---- + ----- + --- + 

obs.: max() helps(return last id , count of id) need name users too, can make on join without subquery , 1 line(limit 1) ?

seem need inner join , group by

select tab.id, tab,name, t2.id, t2.name, count(*) tab inner join  (select id, name, code  user id = (select max(id) user )) t on t.cod = tab.code inner join user uset.code = tab.code group tab.id, tab,name, t2.id, t2.name 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -