简体   繁体   English

基于一个视图连接两个表,sql

[英]Join two tables based on a view, sql

I have the following sql situation我有以下sql情况

Table1
 id name

Table2
 id name

_Table1ToTable2
 id, id_table1, id_table2

Result:
 id, name, table2_name, table2_id

I would like to join Table1 and Table2 into a single query, but I cannot find a way to make a join between them, any ideas?我想将 Table1 和 Table2 连接到一个查询中,但我找不到在它们之间进行连接的方法,有什么想法吗?

if there is no relationship between table1 and table 2 then,如果表 1 和表 2 之间没有关系,则

select table1.id, table1.name, table2.id, table2.name from
table1, table2

if table1 and table2 are related with ID then,如果 table1 和 table2 与 ID 相关,那么,

select  table1.id, table1.name, table2.id, table2.name from
table1
inner join table2
  on table1.id = table2.id

If your intention is to retrieve a result set with every possible combination of the id columns from both tables then you can do as follows:如果您打算从两个表中检索包含 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

If you do not wish to use a temp table an alternative would be to use some variation of the row_number() function.如果您不想使用临时表,另一种方法是使用 row_number() 函数的一些变体。

The above solves for an assumed requirement as your question lacks context.由于您的问题缺乏上下文,因此上述解决了假设的要求。 Elaborate on your requirements and we will be able to provide you with a more relevant and detailed answer.详细说明您的要求,我们将能够为您提供更相关、更详细的答复。

It seems like you want to use bridge table Table1ToTable2 to join Table1 and Table2 .似乎您想使用桥表Table1ToTable2来连接Table1Table2 This can be done simply with 2 INNER JOIN s :这可以通过 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.

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