我正在尝试在MariaDB中进行查询,该查询返回所有团队中玩家的名字。我对查询很陌生,并且没有运气使用内部联接(主要是因为不能很好地理解它),并且所有使用IN的尝试都没有解决那么好,ideias?
编辑:我现在不在我的电脑上,所以我没有关于代码的具体示例,但它就像
SELECT Soccer.player
FROM Soccer
WHERE Soccer.player in (SELECT * FROM Teams, TeamPlayers
WHERE Teams.tid = TeamPlayers.tid);
答案 0 :(得分:2)
您可以这样做:
示例数据
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
);
<强>解释强>
tp.team
字段<强>结果强>
凯蒂
SQLFiddle示例
答案 1 :(得分:1)
SELECT DISTINCT store_type FROM stores s1
WHERE NOT EXISTS (
SELECT * FROM cities WHERE NOT EXISTS (
SELECT * FROM cities_stores
WHERE cities_stores.city = cities.city
AND cities_stores.store_type = stores.store_type));
在NOT EXISTS解释网站上找到了这个例子,效果很好!但是感谢@zedfoxus,希望有一天我能做到这么简单