简体   繁体   中英

Getting records which have only 1 matching row in the joined table?

Consider the following tables:

Persons  
|id   |firstname|lastname|  
|-----|---------|--------|  
|1    |John     |Doe     |  
|2    |Jim      |Smith   |  
|3    |Jane     |Boggard |  
|4    |Joe      |Dash    |  

Licences
|p_id |licence|
|-----|-------|
|1    |car    |
|1    |bike   |
|2    |car    |
|3    |car    |
|3    |bike   |
|1    |plane  |
|4    |bike   |

How can I get the persons who have only 1 associated row in the licences table and which the value is "car" ? (in our case: Jim Smith)

Thanks

The first part of your question is pretty easy (getting a person with only 1 associated row in the licenses table). You just do a GROUP BY , and then HAVING COUNT(*) = 1 :

select
    persons.id
  ,persons.firstname
  ,Persons.lastname
from Persons
    inner join Licenses on
        Licenses.p_id = Persons.`id`
group by
    persons.id
    ,persons.firstname
    ,persons.lastname
having 
  count(*) = 1

The second part of your question is a little tricker: For the people with only 1 license, which have a car license. To do this, you can apply the filter to the HAVING clause, so it's applied after the group by . For example (note the new last line):

select
    persons.id
  ,persons.firstname
  ,Persons.lastname
from Persons
    inner join Licenses on
        Licenses.p_id = Persons.`id`
group by
    persons.id
    ,persons.firstname
    ,persons.lastname
having 
  count(*) = 1
  and min(licenses.licence) = 'car'

You're using the MIN function because you generally need to apply aggregate functions in the HAVING clause. However, since you already know that all these people only have 1 license, the MIN doesn't really make a difference (you could even use MAX with the same results).

This should help to illustrate the process...

SELECT p.*, SUM(l.licence = 'car') cars, COUNT(*) total
  FROM persons p
  JOIN licences l
    ON l.p_id = p.id
 GROUP
    BY p.id;
   +----+-----------+----------+------+-------+
   | id | firstname | lastname | cars | total |
   +----+-----------+----------+------+-------+
   |  1 | John      | Doe      |    1 |     3 |
   |  2 | Jim       | Smith    |    1 |     1 |
   |  3 | Jane      | Boggard  |    1 |     2 |
   |  4 | Joe       | Dash     |    0 |     1 |
   +----+-----------+----------+------+-------+

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