简体   繁体   中英

Get the MySQL record that has less child-records

I have a 2 MySQL tables like that:

Table: WIFI_Spots
*********************
ID  |  Name
1   |  Foo
2   |  Bar

Table: WIFI_Users
*********************
Spot_ID  |  User_ID  |  Status
1        |  3h8n26j  |  active
1        |  h6m78v2  |  inactive
2        |  3v9bn4y  |  active
2        |  6f9ftfx  |  active

In that case i want to get the WIFI spot that has the less active users in it based on status .

So even if there was many inactive users, those wouldn't be counted.

PS In the example, the result would be the Spot 1.

SELECT    COUNT(s.ID)
FROM      WIFI_Spots s
LEFT JOIN WIFI_Users u ON u.Spot_ID = s.ID
WHERE     u.Status = 'active'
GROUP     BY s.ID
ORDER     BY COUNT(u.Spot_ID)
LIMIT     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