MySQL - 组合 2 个具有不同 SET 和 WHERE 子句的查询
不久前@Richard Harris 给出了一个很好的答案对于类似的问题,但我相信我的情况略有不同。
正如您所看到的,我有 2 个连续的 UPDATE 语句针对相同的表和字段,但具有不同的 SET 和 WHERE 子句。
$this->db->query("
UPDATE user_profiles
SET reputation = reputation + 15
WHERE user_id = $answer_author_id;
");
$this->db->query("
UPDATE user_profiles
SET reputation = reputation + 2
WHERE user_id = $user_id;
");
我想知道是否可以将其合并为单个查询,或者是否需要进一步规范化。另外,这些连续查询的效率是否太低了?如果没有,我就不会费心尝试合并到单个查询中。
非常感谢您对此的想法。
A while ago @Richard Harris gave a great answer for a similar question, but I believe my situation is slightly different.
As you can see I have 2 consecutive UPDATE statements targeting the same table and fields but with different SET and WHERE clauses.
$this->db->query("
UPDATE user_profiles
SET reputation = reputation + 15
WHERE user_id = $answer_author_id;
");
$this->db->query("
UPDATE user_profiles
SET reputation = reputation + 2
WHERE user_id = $user_id;
");
I wonder if this can be combined into a single query, or if this requires further normalization. Also, are these consecutive queries too inefficient? If not, I wouldn't bother trying to combine into a single query.
Your thoughts on this are much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
you can do this:
该解决方案实际上与 这个,只是有点嵌套。
The solution actually isn't terribly different from this one, just a tad more nested.
更新用户配置文件
SET 声誉 = 声誉 + IF(user_id=$answer_author_id,15,2)
其中 user_id = $answer_author_id 或 user_id = $answer_author_id;
这可行,但我建议仅出于代码可读性而使用 2 个查询,除非效率非常重要。
UPDATE user_profiles
SET reputation = reputation + IF(user_id=$answer_author_id,15,2)
WHERE user_id = $answer_author_id OR user_id = $answer_author_id;
This works, but I recommend using 2 queries simply for code readability, unless efficiency is super important.