此Update查询尝试使用concat()fun

时间:2019-06-07 15:12:04

标签: mysql sql database

我想通过在其中添加数据来更新该字段,但是它给出了一个错误,请纠正我(下面是“查询”和“表说明”)

我试图用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

1 个答案:

答案 0 :(得分:0)

作为一般规则,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;