简体   繁体   English

如何从同一张表中获取基于实例的结果集?

[英]How do I get a result set based on instances from the same table?

I have a database with the table "Characters" and the table "Planets" from the star wars movies. 我有一个数据库,其中包含《星球大战》电影中的“角色”表和“行星”表。 I need to find out the names of the characters that have the same affiliation as their homeplanet. 我需要找出与本位机有相同隶属关系的角色的名称。 The data is in the following images : 数据在以下图像中:

Characters 人物

在此处输入图片说明

Planets 行星

在此处输入图片说明

I tried this but it doesn't work 我试过了但是没用

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

You need to join characters table to planets table by planet name, then filter rows using same affiliations: 您需要按行星名称将characters表连接到planets表,然后使用相同的从属关系过滤行:

SELECT character_name
FROM characters INNER JOIN planets ON characters.homeworld = planets.planet_name
WHERE characters.affiliation = planets.affiliation;

You need to join the two tables and then constrain by the affiliation. 您需要加入两个表,然后通过从属关系进行约束。 You can add this constraint in the join clause or the where clause, so both of these work: 您可以在join子句或where子句中添加此约束,因此这两个工作都可以:

SELECT character_name
FROM characters c
INNER JOIN planets p ON 
  c.homeworld = p.homeworld
  AND c.affiliation = p.affiliation 

or 要么

SELECT character_name
FROM characters c
INNER JOIN planets p ON 
  c.homeworld = p.homeworld
WHERE c.affiliation = p.affiliation 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在同一个表上合并两个查询以在MySQL中获得单个结果集 - How do I combine two queries on the same table to get a single result set in MySQL 在 MySQL 中,如何根据我对同一张表进行 INNER JOIN 的表的结果进行删除? - In MySQL, how can I do a DELETE based on the result from a table where I did an INNER JOIN with the same table? 如何从表及其子表中获取结果集? - How do I get a result set from a table and its child-tables? 如何从同一表获取基于parent_id的行以与其他行相对应 - How do I get rows to correspond to other rows based on a parent_id , all from the same table 如何根据同一个表上另一个查询的结果集执行查询? - How to perform a query based on the result set of another query on the same table? 如何查询具有相同结构的多个数据库的同一张表并将所有查询结果放在一起? - How do I query same table of several databases with same structure and get all the query result together? 如何设置列的值是使用同一表的列之一的SQL查询的结果 - How do I set the value of a column be a result of a SQL query using one of the columns of the same table 我如何从不同的表和不同的列中获取数据,应将同一列作为结果? - how do I getting data from different table & from different column should make a same column as result? 我如何从具有多个相同值的列的表中获取最新结果 - How can I get the most recent result from a table with a column that has multiple of the same values 如何根据cakephp中其他表的结果从数据库表中获取结果? - How do I get results from a database table based on results from a different table in cakephp?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM