SQL INSERT...SELECT 自动递增 DATETIME [英] SQL INSERT...SELECT with auto-increment DATETIME

查看:64
本文介绍了SQL INSERT...SELECT 自动递增 DATETIME的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有以下结构的表:

I have two tables with the following structure :

userid, entrydatetime, record.

tableA - 有主键 (userid, entrydatetime)

tableB - 没有设置约束.

我正在尝试做一个

INSERT INTO tableA SELECT * FROM tableB ,

但我收到一个错误,因为 tableB 具有完全相同的 useridentrydatetime.

but I am getting an error because tableB has all the same userid and entrydatetime.

例如用户 ID = '12345' 和 entrydatetime = '0000-00-00 00:00:00'.

e.g. userid = '12345' and entrydatetime = '0000-00-00 00:00:00'.

我需要从 tableB 获取的主要数据是 userid 和记录.对于这种情况,entryDateTime 对我来说不太重要.

the main data that I need from tableB are userid and record. entryDateTime is less critical to me for this scenario.

如何合并我的两个表,同时保留我的 tableA 主键约束?有没有办法可以在插入时随机化或自动增加 entrydatetime 字段?

How can I merge my two tables yet keeping my tableA primary key constraint? Is there a way I can randomize or autoincrement the entrydatetime field on insert?

推荐答案

您可以使用以下查询

SET @value = CURRENT_TIMESTAMP();
INSERT INTO tableA 
(user_id, entrydatetime, record) 
(SELECT user_id, @value := @value + INTERVAL 1 SECOND, record from tableB);

希望能帮到你...

这篇关于SQL INSERT...SELECT 自动递增 DATETIME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆