[英]MySQLi UPDATE with Subquery not working
I don't know what's wrong with my query, this subquery works fine when using select but when update it's not working, how do i make a subquery for the update query? 我不知道我的查询出了什么问题,该子查询在使用select时工作正常,但是当更新不起作用时,如何为更新查询创建子查询?
$query = "UPDATE `product`
SET `default` = '0'
WHERE `product_name` = (
SELECT `product_name`
FROM `product`
WHERE `product_id` = {$_GET['bag']}
) AND `product_id` != {$_GET['bag']};
";
$result = mysqli_query($connection, $query); $ result = mysqli_query($ connection,$ query);
MySQL doesn't allow you to refer to the same table you're updating in a subquery. MySQL不允许您引用要在子查询中更新的表。 You have to use a
JOIN
. 您必须使用
JOIN
。
UPDATE product AS p1
JOIN product AS p2 ON p1.product_name = p2.product_name
SET default = '0'
WHERE p2.product_id = {$_GET['bag']}
AND p1.product_id != {$_GET['bag']}
BTW, you should also learn to use prepared queries instead of variable substitution, to prevent SQL injection. 顺便说一句,您还应该学习使用准备好的查询而不是变量替换,以防止SQL注入。
@Barmar beat me to it but here was my answer. @Barmar击败了我,但这是我的答案。
UPDATE `product`
INNER JOIN `product` AS `p` ON `p`.`product_name` = `product`.`product_name` AND `p`.`product_id` = {$_GET['bag']}
SET `default` = '0'
WHERE `product`.`product_id` != {$_GET['bag']};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.