简体   繁体   English

如何连接两个具有不相关列的表 SQL

[英]How to join two tables with unrelated columns SQL

I am trying to join two tables together using UNION (although im not sure that is the best option) there are technically two related columns however they don't have the same name so i'm assuming that isn't an option here is my query:我正在尝试使用 UNION 将两个表连接在一起(虽然我不确定这是最好的选择)在技术上有两个相关的列但是它们没有相同的名称所以我假设这不是我的选择询问:

SELECT title, type, release_date FROM pictures
UNION
SELECT name, residence, NULL as Col3 FROM actor
ORDER BY release_date ASC;

It is only printing out the pictures columns from this?它只是打印出图片列吗? Thank you for any help in advance.感谢您提前提供任何帮助。

To relate two tables you could use some foreign key or a third table in the case of beign a many-to-many relation, you should use one of the join options, for example:要关联两个表,您可以使用一些外键或在多对多关系的情况下使用第三个表,您应该使用连接选项之一,例如:

  • Imagine that exists a table that relate actor and pictures, called actor_pictures.假设存在一个关联演员和图片的表,名为 actor_pictures。
  • Image that we will relate the tables by id (it could be another one, and it doesn't have to have the same name).我们将通过 id 关联表的图像(它可以是另一个,并且不必具有相同的名称)。

You could do this:你可以这样做:

SELECT * FROM actor_pictures ap 
JOIN actor a ON ap.actor_id = a.id 
JOIN pictures p ON ap.pictures_id = p.id
ORDER BY p.release_date ASC

Read this: https://www.w3schools.com/sql/sql_join.asp读这个: https://www.w3schools.com/sql/sql_join.asp

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

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