简体   繁体   English

如何在SQL中设置数据之间的关系限制

[英]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. 因此,我有一个Player表,其中包含PlayerId,firstname,lastname等字段。还有一个Teams表,其中包含TeamId,teamname等字段。我还有一个查找表,通过显示将两个表链接在一起球员在哪支球队上。 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? 我的问题是,如果我想向用户显示尚未超过20人限制的团队,但团队中仍有空间,我该怎么做?

Show teams with quantity of players not exceeding 20: 显示球员人数不超过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

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

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