执行 UPDATE 查询时检查值是否存在
我需要执行一个简单的更新查询,只有在没有具有更新值(item_name)的值时才应执行更新。例如,
数据库表 [item_types]
item_id(PK) | item_name
假设存在 item_id 为 6,我的尝试是
UPDATE item_types as k SET k.item_name = 'item_1' WHERE NOT EXISTS (SELECT * FROM item_types as a WHERE a.item_name = 'item_1') AND k.item_id = '6'
但这给了我错误
"You can't specify target table 'k' for update in FROM clause"
您能否解释一下这里的错误以及如何实现此目的?
谢谢
I need to perform a simple update query where the update should only be done, if there is no value with updating value (item_name). For example,
DB table [item_types]
item_id(PK) | item_name
Assuming there exist item_id with 6, My attempt is
UPDATE item_types as k SET k.item_name = 'item_1' WHERE NOT EXISTS (SELECT * FROM item_types as a WHERE a.item_name = 'item_1') AND k.item_id = '6'
But this gives me error
"You can't specify target table 'k' for update in FROM clause"
Could you please explain the error here and how can I achieve this ?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以对 item_name 字段施加唯一的限制并捕获错误。
You could put a unique restraint on the item_name field and catch the error.
我认为您不能在插入语句中使用表的别名。也可以使用 , 而不是 AND。
尝试
I dont think you can use an alias for a table in an insert statement. Also use , rather than AND.
Try
正如托比建议的,您不能在 UPDATE 行中使用别名。尝试以下语法:
hth, R
As Toby suggested, you can't use an alias in the UPDATE line. Try the following syntax though:
hth, R