如何根据同一个表中的实例获取结果集?

时间:2017-06-02 03:18:36

标签: mysql sql

我有一个数据库,其中有“人物”表和星球大战电影中的“行星”表。我需要找出与其homeplanet具有相同隶属关系的角色的名称。数据如下图所示:

字符

enter image description here

行星

enter image description here

我尝试了这个,但它不起作用

SELECT character_name
FROM characters c1
INNER JOIN characters c2
ON c1.affiliation = c2.affiliation AND c1.homeworld = c2.homeworld
GROUP BY character_name;

2 个答案:

答案 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