我正在尝试在MariaDB中进行查询,以向我返回在所有团队中踢过的球员的姓名。我对查询有点陌生,还没有使用内部联接的运气(大多数时候是因为对它的理解不够好),而所有使用IN的尝试都没有那么好,想法?

编辑:我现在不在我的电脑上,所以我在代码上没有特定的示例,但是就像

SELECT Soccer.player
FROM Soccer
WHERE Soccer.player in (SELECT * FROM Teams, TeamPlayers
WHERE Teams.tid = TeamPlayers.tid);

最佳答案

您可以执行以下操作:

示例数据

create table soccer (player varchar(100));
insert into soccer values ('john'), ('matt'), ('katie');

create table teams (teamname varchar(100));
insert into teams values ('A'), ('B'), ('C');

create table teamplayers (team varchar(100), player varchar(100));
insert into teamplayers values
('A', 'katie'), ('B', 'katie'), ('C', 'katie'),
('B', 'john'), ('C', 'john'),
('C', 'matt');


预期结果

由于katie是所有团队中唯一的球员,因此我们应该打印她的名字。

更轻松的查询

select tp.player
from teamplayers tp
inner join teams t on t.teamname = tp.team
group by tp.player
having count(*) = (select count(*) from teams);


说明


加入团队成员和团队
团体选手(并在having语句中找到计数)
如果人数与球队人数相符,请选择该球员


SQL小提琴

http://sqlfiddle.com/#!9/7110b/15

询问

该查询可以用不同的方式编写。我写的方式希望通过内联解释变得有意义

select player
from soccer s
where not exists (

  select 1
  from

  -- get all possible combinations of team and players
  (select player, teamname from soccer, teams) main

  -- combine the above with team players
  left join teamplayers tp
    on tp.team = main.teamname
    and tp.player = main.player

  -- find those players who DO NOT end up in one or more teams
  -- and exclude those from select (see where NOT EXISTS)
  where tp.team is null
    and main.player = s.player

);


说明


要知道某个人是否在所有团队中,让我们对所有团队中的每个球员进行矩阵分析(每个人都在所有团队中的情况)
将这种情况与teamplayers表进行比较。不在一个或多个团队中的那些球员在tp.team字段中将为NULL
将所有球员与上面的列表进行比较,然后选择那些不在列表中的球员


结果

凯蒂

SQLFiddle示例

http://sqlfiddle.com/#!9/7110b/11

关于mysql - MariaDB寻找一名参加所有团队的足球运动员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41204804/

10-15 18:20