我有一个数据库,其中有“人物”表和星球大战电影中的“行星”表。我需要找出与其homeplanet具有相同隶属关系的角色的名称。数据如下图所示:
字符
行星
我尝试了这个,但它不起作用
SELECT character_name
FROM characters c1
INNER JOIN characters c2
ON c1.affiliation = c2.affiliation AND c1.homeworld = c2.homeworld
GROUP BY character_name;
答案 0 :(得分:0)
您需要按行星名称将characters
表格加入planets
表格,然后使用相同的从属关系过滤行:
SELECT character_name
FROM characters INNER JOIN planets ON characters.homeworld = planets.planet_name
WHERE characters.affiliation = planets.affiliation;
答案 1 :(得分:0)
您需要加入这两个表,然后按联盟约束。您可以在join子句或where子句中添加此约束,因此这两个都可以工作:
SELECT character_name
FROM characters c
INNER JOIN planets p ON
c.homeworld = p.homeworld
AND c.affiliation = p.affiliation
或
SELECT character_name
FROM characters c
INNER JOIN planets p ON
c.homeworld = p.homeworld
WHERE c.affiliation = p.affiliation