Mysql 重复键更新 +子查询
使用这个问题的答案: 需要 MySQL INSERT - SELECT 查询具有数百万条记录的表
new_table
* date
* record_id (pk)
* data_field
INSERT INTO new_table (date,record_id,data_field)
SELECT date, record_id, data_field FROM old_table
ON DUPLICATE KEY UPDATE date=old_table.data, data_field=old_table.data_field;
我需要它与分组和连接一起使用..所以要编辑:
INSERT INTO new_table (date,record_id,data_field,value)
SELECT date, record_id, data_field, SUM(other_table.value) as value FROM old_table JOIN other_table USING(record_id) GROUP BY record_id
ON DUPLICATE KEY UPDATE date=old_table.data, data_field=old_table.data_field, value = value;
我似乎无法更新值。如果我指定 old_table.value 我会收到“未在字段列表中定义”错误。
Using the answer from this question: Need MySQL INSERT - SELECT query for tables with millions of records
new_table
* date
* record_id (pk)
* data_field
INSERT INTO new_table (date,record_id,data_field)
SELECT date, record_id, data_field FROM old_table
ON DUPLICATE KEY UPDATE date=old_table.data, data_field=old_table.data_field;
I need this to work with a group by and join.. so to edit:
INSERT INTO new_table (date,record_id,data_field,value)
SELECT date, record_id, data_field, SUM(other_table.value) as value FROM old_table JOIN other_table USING(record_id) GROUP BY record_id
ON DUPLICATE KEY UPDATE date=old_table.data, data_field=old_table.data_field, value = value;
I can't seem to get the value updated. If I specify old_table.value I get a not defined in field list error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 http://dev.mysql.com/doc 的文档/refman/5.0/en/insert-select.html
因此,您不能使用 select 查询,因为它有一个 group by 语句。你需要改用这个技巧。基本上,这会创建一个派生表供您查询。它的效率可能不是令人难以置信,但它确实有效。
Per the docs at http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
So, you cannot use the select query because it has a group by statement. You need to use this trick instead. Basically, this creates a derived table for you to query from. It may not be incredibly efficient, but it works.
在搜索更多内容时,我发现了一个相关问题:“MySQL ON DUPLICATE KEY UPDATE,唯一键中的列可为空"。
答案是
VALUES()
可用于引用 select 子查询中的“value”列。
While searching around some more, I found a related question: "MySQL ON DUPLICATE KEY UPDATE with nullable column in unique key".
The answer is that
VALUES()
can be used to refer to column "value" in the select sub-query.