我想更新字段并附加数据,但出现错误,请纠正我(查询和表说明如下)
我尝试在 SQL 中使用 CONCAT () FUNCTION 触发 UPDATE 命令。
update products a
set a.des = (select concat((select b.des from products b limit 1) ,' one okay') from a)
where a.p_id = 1;
我用过MySQL, 表说明: mysql> desc 产品;
+---------+-------------+------+-----+--------------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+--------------+-------+
| p_id | int(3) | NO | PRI | 0 | |
| p_name | varchar(10) | YES | | NULL | |
| p_price | int(10) | YES | | NULL | |
| cat_id | int(3) | YES | MUL | NULL | |
| des | varchar(30) | YES | | Good | |
+---------+-------------+------+-----+--------------+-------+
预期输出: mysql> 从产品中选择*;
+------+--------+---------+--------+---------------+
| p_id | p_name | p_price | cat_id | des |
+------+--------+---------+--------+---------------+
| 1 | Mouse | 150 | 3 | Good one okay |
| 2 | LAN | 50 | 4 | Good |
+------+--------+---------+--------+---------------+
2 rows in set (0.00 sec)
输出:
Error - update products a set a.des = (select concat((select b.des from products b limit 1) ,' one okay') from a) where a.p_id = 1 Error Code: 1146. Table 'test.a' doesn't exist 0.437 sec
最佳答案
一般来说,MySQL 不允许您在 update
语句的其余部分引用正在更新的表。
正常的解决方法是将其表述为 JOIN
:
update products p cross join
(select * from products limit 1) arbitrary
set p.des = concat(arbitrary.des, ' one okay')
where p.p_id = 1;
注意别名任意
的使用。您使用的 limit
没有 order by
,因此您得到的是任意描述。
如果您只想将字符串附加到现有描述中,那么您需要更简单的方法:
update products p
set p.des = concat(p.des, ' one okay')
where p.p_id = 1;
关于mysql - 此更新查询尝试使用 concat() fun 更新表有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497014/