mysql - 将串联值插入表中

标签 mysql sql

使用 MYSQL,我可以计算时间差并将其作为串联输出。 我正在使用来自 here. 的查询

WITH difference_in_seconds AS (
  SELECT
    id,
    departure,
    arrival,
    TIMESTAMPDIFF(SECOND, departure, arrival) AS seconds
  FROM travel
),
 
differences AS (
  SELECT
    id,
    departure,
    arrival,
    seconds,
    MOD(seconds, 60) AS seconds_part,
    MOD(seconds, 3600) AS minutes_part,
    MOD(seconds, 3600 * 24) AS hours_part
  FROM difference_in_seconds
)
 
SELECT
id,
departure,
arrival,
CONCAT(
  FLOOR(seconds / 3600 / 24), ' days ',
  FLOOR(hours_part / 3600), ' hours ',
  FLOOR(minutes_part / 60), ' minutes ',
  seconds_part, ' seconds'
) AS difference
FROM differences;

我的输出是这样的:

id  departure           arrival             difference
1   2018-03-25 12:00:00 2018-04-05 07:30:00 10 days 19 hours 30 minutes 0 seconds

我想做的是获取“差异”的串联字符串并更新/插入到另一个表中。在另一个表中,我有一个名为“time_difference”的列,因此我尝试使用更新查询。我还设置了一个条件,它应该只更新到相关的用户配置文件。

    UPDATE airport_database.user
    SET time_difference = (SELECT
  id,
  departure,
  arrival,
  CONCAT(
    FLOOR(seconds / 3600 / 24), ' days ',
    FLOOR(hours_part / 3600), ' hours ',
    FLOOR(minutes_part / 60), ' minutes ',
    seconds_part, ' seconds'
  ) AS difference
FROM differences)
    WHERE name = "Sir"; 

但是,我越来越

Error #1241 - Operand should contain 1 column(s).

因此我也尝试通过以下方式获取连接值:

UPDATE airport_database.user
        SET time_difference = (difference)
        WHERE name = "Sir"; 

我明白了

Error #1054 - Unknown column of 'difference' in 'Field List'.

我想知道为什么我的连接字符串列无法被 MYSQL 检测到。

任何帮助将不胜感激,谢谢。

最佳答案

演示。

CREATE TABLE src (id INT, departure DATETIME, arrival DATETIME);
INSERT INTO src VALUES (1, '2018-03-25 12:00:00', '2018-04-05 07:30:00');
CREATE TABLE dst (id INT, departure DATETIME, arrival DATETIME, verbal_diff VARCHAR(255));
INSERT INTO dst SELECT *, NULL FROM src;
SELECT * FROM dst;
id departure arrival verbal_diff
1 2018-03-25 12:00:00 2018-04-05 07:30:00 null
UPDATE dst
JOIN (SELECT id,
             CONCAT(TIMESTAMPDIFF(DAY, departure, arrival),
                    DATE_FORMAT(TIMEDIFF(arrival, departure), ' days %H hours %i minutes %s seconds')) difference
      FROM src) data USING (id)
SET dst.verbal_diff = data.difference;

SELECT * FROM dst;
id departure arrival verbal_diff
1 2018-03-25 12:00:00 2018-04-05 07:30:00 10 days 19 hours 30 minutes 00 seconds

db<> fiddle here

参见UPDATE Statement , 多表语法。

关于mysql - 将串联值插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70504413/

相关文章:

mysql - has_many 与计数值的关联

mysql - 查询优化: Select min of a result set where a column is max of another set

mysql - 在 MyISAM 表上执行 `ALTER TABLE my_table ENGINE InnoDB` 没有任何效果。为什么?

mySQL - 多行合并为一行

sql - 动态 sql 性能和实现建议?

python - SQL Group By 与 Python Group By 错误对比

mysql - 特定条件匹配后分组

mysql - SQL 计算所有行而不是计算单个行

MySQL外键定义?

php - MYSQL查询有问题