我想通过在其中添加数据来更新该字段,但是它给出了错误,请纠正我(下面是“查询”和“表说明”)
我试图在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;
注意别名
arbitrary
的使用。您正在使用没有limit
的order by
,因此您将获得任意描述。如果只想在现有描述后附加一个字符串,则需要更简单的方法:
update products p
set p.des = concat(p.des, ' one okay')
where p.p_id = 1;
关于mysql - 尝试使用concat()更新表的此Update查询有什么问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56497014/