简体   繁体   中英

How to set a limit on the relationship between data in SQL

So, I have a Player table which has fields like PlayerId, firstname, lastname etc.. and a Teams table with fields such as, TeamId, teamname, etc.. I also have a look up table linking the two tables together by showing which player is on which team. My question is, if I wanted to display to the user the Teams that have not exceeded the 20 Player limit and still have room on the team, how would I go about doing that?

Show teams with quantity of players not exceeding 20:

SELECT t.teamname
FROM team t
LEFT JOIN player_team pt ON
  t.teamid = pt.teamid
GROUP BY t.teamname
HAVING COUNT(pt.playerid) <= 20 -- you probably mean < 20

Add information on slots availability:

SELECT t.teamname, CONCAT(COUNT(pt.playerid), '/20') AS slots_taken -- if 20 is max
FROM team t
LEFT JOIN player_team pt ON
  t.teamid = pt.teamid
GROUP BY t.teamname
HAVING COUNT(pt.playerid) <= 20 -- you probably mean < 20

Considering the below as tables and columns,

player_table
------------
playerid
firstname
lastname

.
teams
-----
teamid
teamname

.
player_team_association
------------------------
teamid
playerid
.

Your query should look like this

select t.teamname, count(pta.playerid) as PlayerLimit,
(20 - PlayerLimit) as AvailableSlots
from teams t,player_team_association  pta
where t.teamid = pta.teamid
group by pta.teamid having PlayerLimit <=20

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