[英]Join two tables based on a view, sql
我有以下sql情況
Table1
id name
Table2
id name
_Table1ToTable2
id, id_table1, id_table2
Result:
id, name, table2_name, table2_id
我想將 Table1 和 Table2 連接到一個查詢中,但我找不到在它們之間進行連接的方法,有什么想法嗎?
如果表 1 和表 2 之間沒有關系,則
select table1.id, table1.name, table2.id, table2.name from
table1, table2
如果 table1 和 table2 與 ID 相關,那么,
select table1.id, table1.name, table2.id, table2.name from
table1
inner join table2
on table1.id = table2.id
如果您打算從兩個表中檢索包含 id 列的所有可能組合的結果集,那么您可以執行以下操作:
select id = identity (int, 1, 1), * into #a from (select distinct table1. id as id1, table2. id as id2 from table1 cross apply table2) d; select * from #a; drop table #a
如果您不想使用臨時表,另一種方法是使用 row_number() 函數的一些變體。
由於您的問題缺乏上下文,因此上述解決了假設的要求。 詳細說明您的要求,我們將能夠為您提供更相關、更詳細的答復。
似乎您想使用橋表Table1ToTable2
來連接Table1
和Table2
。 這可以通過 2 INNER JOIN
簡單地完成:
SELECT
tt.id AS tt_id,
t1.id AS t1_id,
t1.name AS t1_name,
t2.id AS t2_id,
t2.name AS t2_name
FROM
Table1ToTable2 AS tt
INNER JOIN Table1 AS t1
ON t1.id = tt.id_table1
INNER JOIN Table2 AS t2
ON t2.id = tt.id_table2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.