简体   繁体   English

显示两个不同表中的所有列

[英]Displaying all the columns from two different tables

How to display all the columns of two different tables as ONE ? 如何将两个不同表的所有列显示为ONE?

I have two tables, movies and movie_actors in MovieDB. 我在MovieDB中有两个表,电影和movie_actors。 The id of the movies is primary key and id of the movie_actor is foreign key, and movies_actor.id is referenced to movies.id 电影的id是主键, movie_actor id是外键, movies_actor.id被引用到movies.id

   TABLE MOVIES
   id/title/director/genre/year_of_release

   TABLE MOVIE_ACTOR
   id/title/actor/age

I used Union, but its not working, because union is asking for same number of attributes. 我使用了Union,但它不起作用,因为union要求相同数量的属性。 but here the first table has 4 columns and the second has only 3. 但这里第一个表有4列,第二个表只有3列。

I would like to display as in one table 我想在一张表中显示

   id/title/director/genre/year_of_release/actor/age 

any ideas? 有任何想法吗?

You will want to use a join on the tables. 您将需要在表上使用连接。 The join will be between the two fields that are primary/foreign keys to each other which you stated was the id in the movie table and the id in the movie_actor table: 联结将两个字段是主/外键,你说是彼此之间idmovie表和idmovie_actor表:

select m.id,
  a.title,
  m.director,
  m.genre,
  m.year_of_release,
  a.actor,
  a.age
from movies m
inner join movie_actor a
  on m.id = a.id

If you are not familiar with join syntax than here is great visual explanation of joins . 如果您不熟悉连接语法,那么联接的视觉解释很棒。

An INNER JOIN will return the set of records that match in both tables. INNER JOIN将返回两个表中匹配的记录集。 If you had records in the movie table that did not have matching records in the move_actor table, then you would want to use a LEFT JOIN . 如果movie表中的记录在move_actor表中没有匹配的记录,那么您可能希望使用LEFT JOIN This would return all movies even if it did not have records in the movie_actor table: 这将返回所有电影,即使它在movie_actor表中没有记录:

select m.id,
  a.title,
  m.director,
  m.genre,
  m.year_of_release,
  a.actor,
  a.age
from movies m
left join movie_actor a
  on m.id = a.id

See SQL Fiddle with Demo of both queries. 请参阅SQL Fiddle和两个查询的演示

You can join these tables using the following query. 您可以使用以下查询加入这些表。

SELECT MOVIES.id, title, director, genre, year_of_release, actor, age
    FROM MOVIES INNER JOIN MOVIE_ACTOR ON (MOVIE.id = MOVIE_ACTOR.id)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM