SQL Inner Join使用选择而不是表名称

发布于 2025-02-13 20:28:02 字数 428 浏览 0 评论 0原文

我有两个表在表Tab1和tab2上执行内部连接的表格有不同的长度,但在TAB1_COL2和TAB2_COL2(alias_2/alias_4)中具有常见数据,

select
    tab1_col1 as alias_1,
    tab1_col2 as alias_2,
from db.schema.tab1
inner join (
    select
        tab2_col1 as alias_3,
        tab2_col2 as alias_4,
        tab2_colx as alias_x
    from db.schema.tab2
) on db.schema.tab1.alias_2 = db.schema.tab2.alias_4

我一直在遇到错误,但有“ TAB2”的条目,但是在查询的这一部分中无法引用它。

I have two tables that I'm trying to perform an Inner join on tables tab1 and tab2 have different lengths but have common data in tab1_col2 and tab2_col2 (alias_2/alias_4)

select
    tab1_col1 as alias_1,
    tab1_col2 as alias_2,
from db.schema.tab1
inner join (
    select
        tab2_col1 as alias_3,
        tab2_col2 as alias_4,
        tab2_colx as alias_x
    from db.schema.tab2
) on db.schema.tab1.alias_2 = db.schema.tab2.alias_4

I keep on getting the error there is an entry for "tab2" but it can't be referenced in this part of the query.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我为君王 2025-02-20 20:28:02
  1. Don't use 3 part naming its
  2. 您不能在其声明的同一范围中引用列别名(除非在子句中订单中除外),因此您无法在联接条件下访问alias_2。您必须使用实际的列名。
  3. 您无法从外部上下文中访问子查询/派生表中的表名,因此您必须别名并使用该别名。
  4. 最佳实践是简短但有意义的别名提供所有桌子/派生表格 - 它使查询更加清晰。
select
    tab1_col1 as alias_1,
    tab1_col2 as alias_2,
from [schema].tab1 as T1
inner join (
    select
        tab2_col1 as alias_3,
        tab2_col2 as alias_4,
        tab2_colx as alias_x
    from [schema].tab2
) as T2 on T2.alias_4 = T1.tab1_col2;
  1. Don't use 3 part naming its not best practice.
  2. You can't reference a column alias in the same scope its declared (except for in the order by clause) so you can't access alias_2 in your join condition. You have to use the actual column name.
  3. You can't access table names within a sub-query/derived-table from outside that context, so you must alias it and use that alias.
  4. Best practice is give all you tables/derived-tables short but meaningful aliases - it makes the query much clearer.
select
    tab1_col1 as alias_1,
    tab1_col2 as alias_2,
from [schema].tab1 as T1
inner join (
    select
        tab2_col1 as alias_3,
        tab2_col2 as alias_4,
        tab2_colx as alias_x
    from [schema].tab2
) as T2 on T2.alias_4 = T1.tab1_col2;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文