How can I create a view from more than one table?

巧了我就是萌 提交于 2020-01-05 06:42:42

问题


I have to create a view from more than one table in an MS SQL Server database, but I am not able to get the correct syntax for the same.


回答1:


You'll have to provide more information about how you are looking to return data from more than one table. Typically you use JOINs:

CREATE VIEW your_view_vw AS
   SELECT *
     FROM TABLE_A a
     JOIN TABLE_B b ON b.pk = a.fk

...where fk stands for "Foreign Key", and pk stands for "Primary Key" - assuming these constraints are in place. Maybe you need to use a Cross join instead? Here's a great visual representation of JOINs visually.

Reference:

  • CREATE VIEW



回答2:


You do this with JOINs, just like you would with a regular query.

If you can write a query that gets you the data, you should be able to write view nearly the exact same way.

Post what you have.




回答3:


example

create view ViewCustomerOrders
as
select * from Customer c
join Order o on o.CustomerID = c.CustomerID 



回答4:


create view viewname
as
select * from table a
join table b on b.col2 = a.col2



回答5:


create view view_name as select * from table_A a join table_B b on a.column_id = b.column_id



来源:https://stackoverflow.com/questions/2923543/how-can-i-create-a-view-from-more-than-one-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!