简体   繁体   中英

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

Given the following schema http://sqlfiddle.com/#!9/dbc328 I have two tables:

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.

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() .

When trying to use count, such as

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 . 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.

eg the response should be 2 in this case, since the only entries that match our criteria are 1 and 4

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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