如何从查询中设置默认值?

huangapple go评论79阅读模式
英文:

How to set default values from a query?

问题

我需要在我的表中添加一个新的列,该列不能为空,我想从另一个表中设置默认值,这可能吗?

我正在尝试这样做:
ALTER TABLE MY_TABLE ADD NEW_COLUMN AS (SELECT ANOTHER_COLUMN FROM ANOTHER_TABLE WHERE MY_TABLE.FIELD1 = ANOTHER_TABLE.FIELD1)
但是我遇到了一个错误:
在这个上下文中不允许使用子查询。

英文:

I need to include a new column to my table, the column is not nullable, I want to set the default value from another table, is there possible?

I'm trying to do something like that:
ALTER TABLE MY_TABLE ADD NEW_COLUMN AS (SELECT ANOTHER_COLUMN FROM ANOTHER_TABLE WHERE MY_TABLE.FIELD1 = ANOTHER_TABLE.FIELD1)
But I got an error:
Subqueries are not allowed in this context.

答案1

得分: 0

你可以使用多表更新语句来更新一个表中的列值,而不是使用"alter table"语句。在定义连接条件后,可以使用以下语句:

UPDATE D
SET D.NEW_COLUMN = T.ANOTHER_COLUMN
FROM MY_TABLE D
LEFT JOIN ANOTHER_TABLE T
ON D.FIELD1 = T.FIELD1
WHERE (可选地使用条件来仅更新列中的特定行)

英文:

Instead of alter table , you can use Multiple table update statement to update a column value from a column in another table after defining joining condition!

UPDATE D
SET D.NEW_COLUMN = T.ANOTHER_COLUMN
FROM MY_TABLE D 
LEFT JOIN ANOTHER_TABLE T
   ON D.FIELD1 = T.FIELD1
WHERE (Use a condition optionally to just update those rows only in your column)

huangapple
  • 本文由 发表于 2023年8月8日 23:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定