简体   繁体   English

如何将查询结果添加到列中

[英]How to add the result of a query into a column

I have the following query which returns a column of values:我有以下查询返回一列值:

SELECT CONCAT(
  from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
  CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 
  AS SIGNED)
) FROM IEX_Tick;

How can I copy this column to an existing column in the same table?如何将此列复制到同一个表中的现有列?

I believe a subquery would do:我相信子查询会做:

UPDATE IEX_Tick SET SomeColumn = (
   SELECT CONCAT(
       from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
       CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 AS SIGNED)
   ) FROM IEX_Tick;
)

Edit:编辑:
(in response to this comment ) (回应此评论

After doing some research, I found that, even though the suggested solution above is valid SQL , it's not a supported way of updating a table in MySQL .在做了一些研究之后,我发现,即使上面建议的解决方案是有效的SQL ,它也不是在MySQL中更新表的支持方式。

Information I gathered from various related posts here on Stack Overflow (such as this and this ) suggests that MySQL restricts these types of UPDATE queries:我从 Stack Overflow 上的各种相关帖子中收集的信息(例如thisthis )表明MySQL限制了这些类型的UPDATE查询:

... because your update could be cyclical… what if updating that record causes something to happen which made the WHERE condition FALSE? ...因为您的更新可能是周期性的...如果更新该记录导致某些事情发生,从而使 WHERE 条件为 FALSE,该怎么办? You know that isn't the case, but the engine doesn't.您知道情况并非如此,但引擎却并非如此。 There also could be opposing locks on the table in the operation.在操作中,表上也可能有相反的锁。

Therefore, a viable alternative that helps avoid this arbitrary restriction set by MySQL is to use another subquery, this time in your FROM clause, as shown below:因此,有助于避免MySQL设置的这种任意限制的可行替代方案是使用另一个子查询,这次是在您的FROM子句中,如下所示:

UPDATE IEX_Tick SET SomeColumn = (
   SELECT CONCAT(
       from_unixtime(lastSaleTime/1000, '%Y-%d-%m %h:%i:%s.'),
       CAST(EXTRACT(MICROSECOND FROM from_unixtime(lastSaleTime/1000))/1000 AS SIGNED)
   ) FROM (
       SELECT * FROM IEX_Tick AS SomeName
   );
)

Note: I would personally avoid using the SELECT * FROM IEX_Tick , especially if IEX_Tick has many columns.注意:我个人会避免使用SELECT * FROM IEX_Tick ,特别是如果IEX_Tick有很多列。 I good way to optimise the subquery would be to use only the column(s) needed.我优化子查询的好方法是仅使用所需的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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