mysql - 此更新查询尝试使用 concat() fun 更新表有什么问题

标签 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

最佳答案

一般来说,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/

相关文章:

php - 如何确保我的用户数据在 PHP 和 MySQL 中有效?

php - 检查 SQL 表上的数组是否有重复项

MySQL - 使用 BETWEEN 搜索负经度值

SQL:CASE 语句中使用的别名列名

sql - postgres中的模糊全文搜索

javascript - 用于跟踪用户分数历史记录的数据库表

mysql - Go - 连接到外部 mysql 数据库

sql - 为什么创建不相关的索引会使我的查询更快?

mysql - 在 MySQL 中通过分隔符拆分并获取字符串的一部分

jquery - 从 jquery 运行 php 脚本