【问题标题】:what does it mean to have an SQL FROM clause with no comma?没有逗号的 SQL FROM 子句是什么意思?
【发布时间】:2018-03-13 18:41:37
【问题描述】:

我今天注意到这个查询

 select * from table1 table2 where column_from_table1 = ?;

有效。它的工作原理与(返回相同的列)相同

 select * from table1 where column_from_table1 = ?;

前者不应该是语法错误吗?它将table2 解释为什么?

【问题讨论】:

  • 为了记录,无论如何你都不想在from 子句中使用逗号。您应该使用正确、明确、标准的JOIN 语法。

标签: sql syntax


【解决方案1】:

似乎将其解释为重命名表,即使table2 存在它也很高兴允许重命名,这也有效:

 select * from table1 asdf where asdf.column_from_table1 = ?;

【讨论】:

  • 非常有趣的是,如果您将 where 子句限定为 table1.column_from_table1 您将收到您所期望的错误。非常脏的查询
【解决方案2】:
select * from table1 table2 where column_from_table1 = ?;

table2 用作table1 的表别名。它根本没有被用作数据库中对象的名称。存在名为table2 的表这一事实与此查询完全无关。通常你会看到这样的东西:

select t.id, t.name from table1 t where t.column_from_table1 = ?;

某些 RDBMS 需要 as 关键字,因此您还会看到:

SELECT t.id, t.name FROM table1 AS t WHERE t.column_from_table1 = ?;

表别名对于简化编写具有多个表的查询很有用,尤其是当它们具有需要限定的共享列名时。它们对于表连接到自身的自连接也是必不可少的。

使用别名的连接示例:

SELECT t1.Id,
    t1.Name as t1_Name
    t2.Name as t2_Name
FROM table1 t1
    JOIN table2 t2
        ON t1.id = t2.id
WHERE t1.column_from_table1 = ?;

或者,对于自联接来查找重复的 Name 值,例如:

SELECT t1.Name,
    t1.Id
    t2.Id as Dupe_Id
FROM table1 t1
    JOIN table1 t2
        ON t1.Name = t2.Name
WHERE t1.Id < t2.Id;

请注意,此查询引用了两次table1,并使用t1t2 的别名来区分它所指的是哪个。

请注意,FROM table1, table2 WHERE table1.id = table2.id 等逗号连接是非常古老的语法,在编写查询时应明确避免使用。较旧的语法难以阅读和维护,并且不支持外部连接,除非通过特定于供应商的扩展。带有 JOIN 关键字的新语法于 1992 年在标准 SQL 中引入。没有理由仍然使用逗号连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多