SQL从多个表中检索数据 [英] SQL Retrieve data from multiple tables
问题描述
我有2个表,我想用一个存储过程从两个表中检索数据。
第二个表有多行链接到一个排在第一桌。
表1
Field 1 < br $>
Field 2
Field 3
表2
Field 1_1
Field 2_1
Field 3_2
Field 4_2
Field 5_3
Field 6_3
表格通过PK和FK链接
字段1_1,指第二个表字段(字段1)链接到第一个表字段(_1)
我的问题是...我想从单个存储过程查看两个表中的数据,当我执行存储过程时,结果应如下所示:
字段1 - Field 1_1
Field 1 - Field 2_1
Field 2 - Field 3_2
Field 2 - Field 4_2
等等...
到目前为止我尝试了什么...
I have 2 tables, I want to retrieve the data from both tables with a single stored procedure.
The 2nd table has multiple rows that link to a single row in the 1st table.
Table 1
Field 1
Field 2
Field 3
Table 2
Field 1_1
Field 2_1
Field 3_2
Field 4_2
Field 5_3
Field 6_3
The tables are linked via a PK and FK
Field 1_1, refers to the 2nd tables field (Field 1) linking to the 1st tables field (_1)
My question is ... I would like to view data from both tables from a single stored procedure, when i execute the stored procedure the result should be as follows:
Field 1 - Field 1_1
Field 1 - Field 2_1
Field 2 - Field 3_2
Field 2 - Field 4_2
etc...
What i have tried so far...
Create Proc usp_Test
As
Select t1.Field1, t1.Field2, t1.Field3, t2.Field1, t2.Field2, t2.Field3, etc
From tbl_Table1 t1 right outer join tbl_Table2 t2 on t1.PK = t2.FK
请帮忙......
Please help...
推荐答案
我认为可以通过使用来实现简单INNER JOIN
I think that can be achieved by using simple INNER JOIN
SELECT
TABLE1_FIELD, TABLE3_FIELD
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1_FIELD = TABLE2_FIELD
Create Proc usp_Test
As
Select t1.Field1, t1.Field2, t1.Field3, t2.Field1, t2.Field2, t2.Field3, etc
From tbl_Table1 t1 left outer join tbl_Table2 t2 on t1.PK = t2.FK
Order By t1.Field1
这篇关于SQL从多个表中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!