简体   繁体   English

我如何“计数” mysql中的列之前如何检索最后的id值?

[英]How to retrieve the last id value before i “count” a column in mysql?

When i select the values of two tables 当我选择两个表的值时

SELECT 
   tab.id
   ,tab.name
   ,tab2.id
   ,tab2.name
   ,count(distinct tab3.id) as totalusers
FROM master tab
  LEFT JOIN user as tab2 ON tab.id = tab2.cod
  LEFT JOIN user as tab3 ON tab.id = tab3.cod
WHERE tab.id = 5 limit 1
ORDER BY tab2.id DESC

OR 要么

SELECT 
   tab.id
   ,tab.name
   ,tab2.id
   ,tab2.name
   ,count(tab2.id)
FROM master tab
  LEFT JOIN user as tab2 ON tab.id = tab2.cod
WHERE tab.id = 5 limit 1
ORDER BY tab2.id DESC

i got 我有

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

But the tab2.id retrieve the first value of table, the order doesn't works when i count the value, how do i get the last key 134 and his name ? 但是tab2.id检索表的第一个值,当我计算该值时,该顺序不起作用,如何获得最后一个键134和他的名字?

users 使用者

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

Obs.: the MAX() helps( Return last id and count of id ) but i need the name from users too, can i make it on where join without a subquery and with one line(limit 1) ? 观察:MAX()可以帮助( 返回最后一个id和id的计数 ),但是我也需要用户的名字,我可以在没有子查询且只有一行(限制1)的情况下在连接处添加它吗?

seem you need inner join and group by 似乎您需要内部加入和分组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM