gpt4 book ai didi

MySQL 跨多个表的 IF 语句

转载 作者:行者123 更新时间:2023-11-30 01:31:59 25 4
gpt4 key购买 nike

我正在尝试使用 IF 语句对 MySQL 表执行多次更新,其中 IF 语句的条件与我正在更新的表位于不同的表中。例如,我正在使用表 2 中的检查更新表 1。

MySQL 返回一个错误,表示无法找到“table2.col1”。表和列都存在,所以我不确定为什么会收到此错误..

cursor = database.cursor() 
cursor.execute("""UPDATE table1 SET col1 = IF(table2.col1= 2, 3 , table1.col1),
col2 = IF(table2.col1= 2 ,%s , table1.col2),
col3 = IF(table2.col1= 2 , %s , table1.col3),
col4 = IF(table2.col1= 2 , %s , table1.col4)
WHERE id =%s""", (val2, val3, val4, id))
database.commit()

错误:

  _mysql_exceptions.OperationalError: (1054, "Unknown column 'table2.col1' in 'field list'")

最佳答案

您需要加入 table2 。试试这个

    UPDATE table1 INNER join table2
ON ....
SET col1 = IF.....

关于MySQL 跨多个表的 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17341052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com