SQL插入语句中表名的别名
是否可以为我要插入值的表指定别名?
我想在嵌套查询中指定一个条件,而表格太冗长了...
比如将这个:
INSERT INTO my_table_with_a_very_long_name (col_a, col_b, col_c)
SELECT foo, bar, baz
FROM other_table
WHERE
other_table.some_value >
(SELECT max(other_value) FROM my_table_with_a_very_long_name);
变成这个:(
INSERT INTO my_table_with_a_very_long_name AS t (col_a, col_b, col_c)
SELECT foo, bar, baz
FROM other_table
WHERE
other_table.some_value > (SELECT max(other_value) FROM t);
显然我的案例更长并且涉及更多参考文献)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不是为表设置别名,而是为表引用的实例设置别名。
这允许自连接等,因为您有多个引用同一物理表的实例。这并不是每个
AS
在其他地方给该表一个新名称,它只是一个引用该特定引用的别名。在您的情况下,有两个显示停止符...
插入的表本身不是选择查询的一部分,它不是与
foo
相同的引用集,<例如,code>bar 或baz
。所以,你根本不能给它起别名(因为没有必要,它永远不会被引用)。另外,即使是,您也不能通过别名引用整个表。您引用一个字段,作为遍历集合的查询的一部分。例如,这也不起作用...
您可以使用...来绕过后一个示例,
但这仍然让我们回到第一点,插入的表永远不会在语句的查询部分中被引用。
我能想到的接近的唯一方法是创建一个视图......
You don't alias a table, you alias an instance of a table reference.
This allows self joins, etc as you have mutliple instances of references to the same physical table. It's not a case where each
AS
gives that table a new name elsewhere, it's just an alias to refer to That particular reference.In your case, there are two show stoppers...
The table being inserted into isn't itself part of the select query, it's not a referenced set in the same way as
foo
,bar
orbaz
for example. So, you can't alias it at all (because there's no need, it can never be referenced).Also, even if it was, you can't reference the whole table through an alias. You reference a field, as part the query itterating through the set. For example, this doesn't work either...
You can get around the latter example using...
But that still brings us back to the first point, the table being inserted into never gets referenced in the query part of your statement.
The only way I can think of getting close is to create a view...
我认为答案是否。
tableName
之后没有AS
参考
更新
AS
子句自 版本 9.5,尽管正如上面 @MatBailie 所指出的,嵌套意味着您需要为INSERT
查询和SELECT
子查询指定别名- 单独查询,否则事情会破裂。例如:I think the answer is NO. There is no
AS
after thetableName
Reference
Update
The
AS
clause became part of PostgreSQL as of version 9.5, though as @MatBailie notes above, the nesting means you'll need to alias theINSERT
query and theSELECT
sub-query separately or things will break. e.g.:正如其他人所说,您不能将名称别名作为 INSERT INTO 语句的一部分。您需要将其放入
WHERE
语句的子查询中。As others have said, you cannot alias the name as part of the
INSERT INTO
statement. You would need to put it in the subquery in theWHERE
statement.