MySql 一次更新两个表
我有两个表需要完全相同的值来实现非规范化目的。
这是查询。
第一个表
UPDATE Table_One
SET win = win+1, streak = streak+1, score = score+200
WHERE userid = 1 AND lid = 1 LIMIT 1
第二个表
UPDATE Table_Two
SET win = win+1, streak = streak+1, score = score+200
WHERE userid = 1 LIMIT 1
正如您所看到的,两个表之间的唯一区别是它们的名称,并且第二个表没有字段 lid
无论如何,要将两个更新合并为一个?
I have two tables that need the exact same values for denormalization purposes.
Here's the query.
first table
UPDATE Table_One
SET win = win+1, streak = streak+1, score = score+200
WHERE userid = 1 AND lid = 1 LIMIT 1
second table
UPDATE Table_Two
SET win = win+1, streak = streak+1, score = score+200
WHERE userid = 1 LIMIT 1
As you can see the only difference between both tables is their name and table two doesn't have the field lid
Anyway to combine both updates to just one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们是两个独立的查询,因此必须如此对待。很抱歉这么说,但是如果您要更新两个具有相同数据的表,可能有更好的方法来设计数据库。请记住保持您的节目干燥。
编辑:应该撤回该内容;您可以将其用于多个表,但不能使用
ORDER BY
或LIMIT
。They’re two separate queries and so must be treated as such. Sorry to say it, but if you’re updating two tables with identical data, there’s probably a better way to design your database. Remember to keep your programming DRY.
Edit: Should retract that; you can use it for multiple tables, but you can’t use
ORDER BY
orLIMIT
.如果您可以连接这些表,那么您可以创建两个表的视图,然后通过该视图进行更新。在您的示例中,userid 看起来可能是合适的键。
在创建视图时,您需要遵循以下内容:指南。
If you can join the tables, then you could create a view of two tables, then update via that view. In your example it looks like userid might be a suitable key.
In creating the view, you'd need to stick to the following guidelines.
如果从 Table_One 到 Table_Two 存在一对一或一对多关系,则可以使用以下方法:
If there is a one to one or one to many relation from Table_One to Table_Two, this would work:
如文档中所述,应该可以进行多表更新。
http://dev.mysql.com/doc/refman/5.5/en/update.html< /a>
注意:多表不支持 LIMIT,因此这可能会导致更多的麻烦,具体取决于细节。
存储过程或事务可能是更好的解决方案。
It should be possible with a multi-table update, as described in the documentation.
http://dev.mysql.com/doc/refman/5.5/en/update.html
Note: Multi-table doesn't support LIMIT, so this could cause more grief depending on the details.
Stored procedures or transactions may be a nicer solution.