首页 > 解决方案 > Sql Query 查找参加过所有锦标赛的球队?

问题描述

我的架构是:

  1. 国家(国家名称**(主键)**)
  2. 锦标赛(年,日期)具有复合主键(年,日期)
  3. 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 年)?卡在这个查询上,我是一名学生,正在寻找这个查询的解决方案,所以请让我知道它可能或没有任何好的线索?

标签: mysqldatabase

解决方案


如果 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)

推荐阅读