简体   繁体   English

MySQL-计算在另一个表中具有条目的元素(内部联接)

[英]MySQL - count elements having entries in another table (inner join)

Given the following schema http://sqlfiddle.com/#!9/dbc328 I have two tables: 给定以下架构http://sqlfiddle.com/#!9/dbc328,我有两个表:

names 名字

id
name

and

addresses 地址

id
nameId
address

I need to find out how many resources in names have a certain number of addresses, for instance 3 addresses each. 我需要找出names有多少资源具有一定数量的地址,例如每个资源3个地址。

Using the following query: 使用以下查询:

SELECT n.id
FROM `names` n
INNER JOIN `addresses` a on a.nameId = n.id
group by n.id
having count(a.id) = 3

I can find out which are those names, but I need a count() . 我可以找出那些名字,但是我需要一个count()

When trying to use count, such as 尝试使用count时,例如

SELECT count(n.id) as cnt
FROM `names` n
INNER JOIN `addresses` a on a.nameId = n.id
group by n.id
having count(a.id) = 3

is not working because I'm using group by . 无法使用,因为我正在使用group by I know I could achieve this by using nested queries, but I want to know whether it can be accomplished using a single query . 我知道我可以通过使用嵌套查询来实现,但是我想知道是否可以使用单个查询来实现。

EDIT: The expected response should be a single row containing a single field 'cnt' that should return the number of names having 3 addresses each. 编辑:预期的响应应该是包含单个字段'cnt'的一行,该字段应返回每个具有3个地址的名称的数量。

eg the response should be 2 in this case, since the only entries that match our criteria are 1 and 4 例如,在这种情况下,响应应该为2 ,因为符合我们标准的唯一条目是14

EDIT: Here's the nested query that's working 编辑:这是工作的嵌套查询

select count(n.id) as cnt
from `names` n
where n.id IN (SELECT n.id
FROM `names` n
INNER JOIN `addresses` a on a.nameId = n.id
group by n.id
having count(a.id) = 3)

I want to achieve the same thing WITHOUT having to use a nested query 我想实现相同的事情而不必使用嵌套查询

Thanks, Daniel 谢谢,丹尼尔

SELECT COUNT(*) AS total
FROM
  (SELECT a.nameId
   FROM `names` n
   INNER JOIN `addresses` a ON a.nameId = n.id
   GROUP BY n.id
   HAVING count(a.id) = 3) AS TEMP

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

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