mysql - 从选择 MySQL 更新

标签 mysql phpmyadmin mariadb

我正在尝试更新“%2017-08-01%”和 "%2017-08-07%"改为交易表中 e.auto="true"的下一个日期 "%2017-08-07%"的金额。然而,mysql正在返回

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM user as u JOIN e_wallet as e ON e.id = u.ewallet JOIN transacti' at line 1

update t set t.amount = (
                          select t.amount 
                          FROM user as u 
                          JOIN e_wallet as e ON e.id = u.ewallet 
                          JOIN transaction as t on t.user = u.id 
                          where e.auto="true" 
                                and t.create_date like "%2017-08-07%"
                        ) 
FROM user as u 
JOIN e_wallet as e ON e.id = u.ewallet 
JOIN transaction as t on t.user = u.id 
where e.auto="true" 
      and t.create_date BETWEEN "%2017-08-01%" and "%2017-08-07%"

最佳答案

如果您忽略子查询,您的 UPDATE 查询将如下所示:

UPDATE t
SET t.amount = ...
FROM user AS u ...
JOIN e_wallet AS e ...

UPDATE 查询中不能有 FROM 子句,这就是导致语法错误的原因。语法为:

UPDATE tablename AS t1
JOIN tablename2 AS t2 ON ...
JOIN tablename3 AS t3 ON ...
SET ...
WHERE ...

所以应该是:

UPDATE transaction AS t
JOIN user AS u ON u.id = t.user
JOIN e_wallet AS e ON e.id = u.ewallet
SET t.amount = (
  select t.amount 
  FROM user as u 
  JOIN e_wallet as e ON e.id = u.ewallet 
  JOIN transaction as t on t.user = u.id 
  where e.auto="true" 
        and t.create_date like "%2017-08-07%"
) 
WHERE e.auto = "true"
AND t.create_date BETWEEN "2017-08-01" and "2017-08-07"

这应该可以解决语法错误,但我不确定它会做你想要的事情。子查询与主查询没有关联,因此它将返回满足条件的所有交易的金额。但是,当您使用子查询作为表达式时,它最多只能返回一行。您可能只想再次加入 transaction 表。

UPDATE transaction AS t
JOIN user AS u ON u.id = t.user
JOIN e_wallet AS e ON e.id = u.ewallet
JOIN transaction AS t1 ON t1.user = t.user
SET t.amount = t1.amount
WHERE e.auto = "true"
AND t.create_date BETWEEN "2017-08-01" and "2017-08-07"
AND t1.create_date LIKE '%2017-08-07%'

关于mysql - 从选择 MySQL 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46234053/

相关文章:

python - PyQt4 问题和在 Python 中登录 WIndow 到主窗口

mysql - 多条记录的外键

Windows 上的 MariaDB - 尝试启动数据库引擎时出现什么错误?

mysql - 使用 2 个连接和 group by 子句优化 mysql 查询

Mysql错误分隔符: Error at Line Delimiter

mysql - Varchar 字符长度

mysql - sql查询选择每个用户的最新条目

mysql - 插入具有外部约束的 UUID 列失败

mysql - 为什么这个 MySQL 语句不起作用?

mysql - ActiveRecord 将 'AND (1=0)' 追加到查询末尾