简体   繁体   中英

Create view by selecting different columns from multiple tables in SQL server

Im trying to create a view where specific Columns from 2 tables to be combined.

My Tables

Table1(Column1,Column2,Column3)

Table2(Column4,Column5,Column6)

Expected output

View1(Column2,Column3,Column6)

What query can i use to achieve that output?

CREATE VIEW [dbo].[View]
AS 
SELECT a.Column2,a.Column3,b.Column6 
FROM Table1 AS a
INNER JOIN Table2 AS b ON A.ID = B.ID -- your logic 

As Fourat and jarhl commented above, you need to explicitly define what columns are used to JOIN both tables. So using the below code change the ID column to the column that relates these two tables, and if it's more than one column the list them all separated by AND.

CREATE VIEW dbo.YourViewName
AS

SELECT t1.Column2, t1.Column3, t2.Column6
FROM Table1 t1
   JOIN Table2 t2 ON t1.ID = t2.ID
GO

If you have and id to join tables:

create view View1
select t1.column2, t1.column3, t2.column6
from table1 t1
join table2 t2 on t1.id = t2.id

If you don't have and id and want to get mixes columns without relationships:

create view View1
select t1.column2, t1.column3, t2.column6
from table1 t1
cross join table2 t2 on t1.id = t2.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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