mysql - Sql Query 查找参加过所有锦标赛的球队?
问题描述
我的架构是:
- 国家(国家名称**(主键)**)
- 锦标赛(年,日期)具有复合主键(年,日期)
- team(ID,Year,Country) 有复合 PK (ID,year,Country)
锦标赛表中的数据为:
CREATE TABLE `tournament` (
`Year` date NOT NULL,
`Country` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `tournament` (`Year`, `Country`) VALUES
('2015-12-17', 'Canada'),
('2015-12-17', 'USA'),
('2016-12-17', 'Canada'),
('2016-12-17', 'USA'),
('2017-12-17', 'UK'),
('2017-12-17', 'USA'),
('2018-12-17', 'China'),
('2018-12-17', 'USA'),
('2019-12-17', 'Australia'),
('2019-12-17', 'USA');
ALTER TABLE `tournament`
ADD PRIMARY KEY (`Year`,`Country`),
ADD KEY `country_tournament_FK` (`Country`);
ALTER TABLE `tournament`
ADD CONSTRAINT `country_tournament_FK` FOREIGN KEY (`Country`) REFERENCES `country` (`Name`);
COMMIT;
团队表中的数据:
CREATE TABLE `team` (
`Year` date NOT NULL,
`ID` int(50) NOT NULL,
`Country` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `team` (`Year`, `ID`, `Country`) VALUES
('2015-12-17', 6, 'Australia'),
('2016-12-17', 2, 'Canada'),
('2019-12-17', 1, 'China'),
('2016-12-17', 1, 'UK'),
('2017-12-17', 2, 'UK'),
('2015-12-17', 5, 'USA'),
('2016-12-17', 5, 'USA'),
('2017-12-17', 5, 'USA'),
('2018-12-17', 5, 'USA'),
('2019-12-17', 5, 'USA');
ALTER TABLE `team`
ADD PRIMARY KEY (`Year`,`ID`),
ADD KEY `team_country_fk` (`Country`);
ALTER TABLE `team`
ADD CONSTRAINT `team_country_fk` FOREIGN KEY (`Country`) REFERENCES `country` (`Name`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `team_tournament_fk_final` FOREIGN KEY (`Year`) REFERENCES `tournament` (`Year`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
我想选择那些参加过所有比赛的球队(平均从 2015 年到 2019 年)?卡在这个查询上,我是一名学生,正在寻找这个查询的解决方案,所以请让我知道它可能或没有任何好的线索?
解决方案
如果 id 是自动编号并且每个国家/地区只有 1 个团队,则类似这样的事情。
select country
from team
group by country
having Count(*)=(select count(distinct year) from tournament)
如果 id 是一个团队的 id 并且你有另一个表“团队”,其中 id 是这个表的外键,你有这样的东西
select team.id
from team
group by team.id
having Count(*)=(select count(*) from tournament)
推荐阅读
- android - Firebase 错误。请确保您的 Firebase 名称拼写正确
- javascript - 嵌套 JSON 文件中的值
- javascript - Firebase 部署到另一个站点
- delphi - GetThreadLocale 与 Delphi 中的语言环境覆盖键不一致
- excel - 使用外部引用将字符串转换为公式
- python - 更改子类的父类的未知属性
- c++ - 如何在 Linux 上使用 Steamworks SDK 编译脚本?
- c# - 如何将所选 Datalist 变量的值从 html 传输到代码隐藏中的 c# 方法?
- jmx - 在 JMX 键中使用通配符获取队列属性列表
- mysql - MySQL“连接”显示的数字太高 - 显示状态