如何在单个查询中执行多个语句来更新mysql中的表

时间:2018-01-15 09:11:50

标签: mysql

我想运行两个select语句并将值传递给if条件并执行更新查询。当我在没有更新查询的情况下运行时,它正在运行。

没有更新查询:(正常工作)

select (select @acc_id := account_id from table1 where book='xyz') as tab1, (select
@id := account_id from table2 where account_id = (select
@acc_id)) as tab2, (select if(((select @acc_id) = (select @id)), 'Valid', 'Invalid')) as test;

使用更新查询:(不工作)

select (select @acc_id := account_id from table1 where book='xyz') as tab1, (select
@id := account_id from table2 where account_id = (select
@acc_id)) as tab2, (select if(((select @acc_id) = (select @id)), (update table1 as t1 join table2 as t2 on t1.account_id=t2.account_id set t2.index1='value1', t2.index2='value2' where t1.book in ('xyz')), 'Invalid')) as test1;

我引用一些线程,但我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可能只需要一个简单的更新声明

MariaDB [sandbox]> select * from table1;
+------------+------+
| account_id | book |
+------------+------+
|          1 | xyz  |
+------------+------+
1 row in set (0.00 sec)

MariaDB [sandbox]> select * from table2;
+------------+--------+--------+
| account_id | index1 | index2 |
+------------+--------+--------+
|          2 | NULL   | NULL   |
|          1 | NULL   | NULL   |
+------------+--------+--------+
2 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> update table1 t1 join table2 t2 on t2.account_id = t1.account_id
    -> set index1 = 'valu1',index2 = 'valu2'
    -> where t1.book = 'xyz';
Query OK, 1 row affected (0.07 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from table2;
+------------+--------+--------+
| account_id | index1 | index2 |
+------------+--------+--------+
|          2 | NULL   | NULL   |
|          1 | valu1  | valu2  |
+------------+--------+--------+
2 rows in set (0.00 sec)