我正在开发一个可以合成的数据库,如:
TAB1: NICK, COUNTRY
TAB2: PLAYER, FRIEND
在TAB2中,PLAYER和FRIEND都可以连接到相应的TAB1.NICK; NICK是主键,PLAYER和FRIEND都是外键。
我需要找到有多少玩家只是来自同一个国家的朋友,但是,在几个下午之后,我仍然无法做到这一点......
我尝试过的最后一件事:
select count(*) from TAB1 as p1
join TAB2 as f1 on p1.nick = f1.player
join TAB1 as p2 on f1.friend = p2.nick
where p1.country is not null and p2.country is not null
and p1.country = p2.country
and not exists (select * from TAB1 as p0
join TAB2 as f0 on p0.nick = f0.nick
join TAB1 as p3 on f0.friend = p3.nickname
where p0.country is not null and p3.country is not null
and p0.country <> p3.country)
答案 0 :(得分:3)
建立查询 - 从更容易的部分开始,并继续更难。使其工作的关键观察是您需要对同一个表使用两个连接。此查询提供两个人来自同一国家/地区的对的列表:
SELECT p1.nick, p1.country, p2.nick, p2.country
FROM tab2
JOIN tab1 AS p1 ON tab2.player = p1.nick
JOIN tab1 AS p2 ON tab2.friend = p2.nick
WHERE p1.country = p2.country
这会计算来自同一个国家/地区的一位或多位朋友的玩家数量:
SELECT COUNT(DISTINCT p1.nick)
FROM tab2
JOIN tab1 AS p1 ON tab2.player = p1.nick
JOIN tab1 AS p2 ON tab2.friend = p2.nick
WHERE p1.country = p2.country
而且,如果你所追求的是那些只有来自同一国家的朋友的人(如评论中所建议的那样),那么你需要确定玩家没有朋友,而朋友的国家不是球员的国家。你进入了一个有趣的问题:一些没有朋友的人会被计算在内吗?由于他们没有来自同一个国家/地区的朋友,因此不会按以下查询计算:
SELECT COUNT(DISTINCT p1.nick)
FROM tab2
JOIN tab1 AS p1 ON tab2.player = p1.nick
JOIN tab1 AS p2 ON tab2.friend = p2.nick
WHERE p1.country = p2.country
AND NOT EXISTS
(SELECT *
FROM tab2 AS t2
JOIN tab1 AS p3 ON t2.player = p3.nick
JOIN tab1 AS p4 ON t2.friend = p4.nick
WHERE p3.country != p4.country
AND p3.nick = p1.nick
)
这说“玩家至少有一个来自他们自己国家的朋友,而且来自不同国家的玩家没有朋友”。
答案 1 :(得分:1)
SELECT TAB2.PLAYER, TAB1.COUNTRY
FROM TAB2 PLAYER_TAB2
JOIN TAB1 PLAYER_TAB1 ON TAB1.NICK = TAB2.PLAYER
WHERE NOT EXISTS (SELECT NULL
FROM TAB2
JOIN TAB1 ON TAB1.NICK = TAB2.FRIEND
AND TAB1.COUNTRY != PLAYER_TAB1.COUNTRY
WHERE TAB2.PLAYER = PLAYER_TAB2.PLAYER)