如何在i" count"之前检索最后一个id值。 mysql中的一列?

时间:2016-07-25 18:06:05

标签: mysql sql count max

当我选择两个表的值时

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

我得到了

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

tab2.id 检索表格的第一个值,当我计算值时,订单不起作用,我如何获得最后一个键 134 和他的名字?

用户

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

Obs。:MAX()帮助(Return last id and count of id),但我也需要用户的名字,我可以在没有子查询和一行(限制1)的情况下进行连接吗?

1 个答案:

答案 0 :(得分:1)

似乎你需要内部联接和分组

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