在另一个 table 中获取所有用户及其记录数

fetch all users and their number of records in another table

我有两个 tables users (user_id, name) 和 license (license_id,user_id)

我想获得所有用户及其在许可 table 中的记录数。 问题看起来很简单,但我无法弄清楚它的查询。

我试过

SELECT * FROM `users` a left join license b on a.user_id=b.user_id

但这给了我 a 的所有行和 b 的匹配行 table,而我想要 a 的所有行和另一列的行数在 b 中匹配。

请帮助我如何获得这个。

如果你想要匹配用户的数量,你应该使用 count 和 group by

SELECT user_id, name, count(*)
FROM `users` a 
INNER join license b on a.user_id=b.user_id
Group by user_id, name

你只想要匹配的计数

select count(*) 
FROM `users` a 
INNER join license b on a.user_id=b.user_id

改为 return 许可证中的数量

  select count(*) 
  FROM `users` a 
  LEFT join license b on a.user_id=b.user_id 

然后您只需使用

即可获得相同的数字
  select count(*) 
  from  license 

否则,如果你想用中音编号,用户不匹配,然后尝试

SELECT user_id, name, ifnull(count(*), 0)
FROM `users` a 
LEFT join license b on a.user_id=b.user_id
Group by user_id, name

试试这个查询:

SELECT a.user_id, a.name, COUNT(b.user_id)
  FROM `users` a 
  LEFT JOIN license b ON a.user_id=b.user_id
  GROUP BY user_id, NAME;

输出:SEE DEMO HERE

SELECT 
  U.user_id, U.name, COUNT(L.license_id) as licenseCount
FROM `users` U
LEFT JOIN license L ON U.user_id=L.user_id
GROUP BY U.user_id;

Refer Sql Fiddle