简体   繁体   English

在sql中从两个表中添加两列

[英]Adding two columns from two tables in sql

I have two tables called owner and condo_unit and I need to get selected information from both of the tables.我有两个名为ownercondo_unit表,我需要condo_unit两个表中获取选定的信息。 These are my two tables below:这是我下面的两个表:

Owner所有者

OwnerNum, LastName, FirstName, Adress

Condo_Unit公寓_单元

Condo_ID, LocationNum, OwnerNum

How do I get one of the OwnerNum , LastName and LocationNum ?如何获得OwnerNumLastNameLocationNum I'm struggling with this since there is an OwnerNum in each of the tables.我正在为此苦苦挣扎,因为每个表中都有一个OwnerNum Just started learning SQL so I'm a bit confused on how to do so.刚开始学习 SQL,所以我对如何学习有点困惑。 If anyone can help that would be great.如果有人可以提供帮助,那就太好了。

You can do Inner Join/Join .你可以做Inner Join/Join

SELECT
        o.OwnerNum,
        o.LastName,
        cu.LocationNum
FROM
        owner o -- o and cu (below) are alias for owner and condo_unit table respectively, you can use owner.ownerNum too, but it becomes messy when used with lot of tables and tables with big names 
JOIN
        condo_unit cu
        ON cu.ownernum = o.ownernum -- this line joins two tables on a common column/id and retrieves common records for the selected columns

Joins help you to conditionally select common data from multiple tables.联接可帮助您有条件地从多个表中选择公共数据。 There are multiple joins like Left Join, Right join, Inner Join.有多个联接,如左联接、右联接、内联接。 It's good that you are learning them - they are very important for any kind of web-development and also for writing complex queries later on in the career.学习它们很好 - 它们对于任何类型的 Web 开发以及在职业生涯后期编写复杂的查询都非常重要。

For starters you can follow this: https://www.w3schools.com/sql/sql_join.asp对于初学者,您可以按照以下步骤操作: https : //www.w3schools.com/sql/sql_join.asp

Just join :只需join

select o.ownernum, o.lastname, cu.locationnum
from owner o
inner join condo_unit cu on cu.ownernum = o.ownernum

Use join query使用连接查询

  SELECT 
OW.OWNERNUM,
OW.LASTNAME,
CO.LOCATIONNUM
FROM OWNER OW INNER JOIN CONDO_UNIT CO 
ON OW.OWNERNUM=CO.OWNERNUM

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

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