我用以下查询创建了一个表:
CREATE TABLE `dailydata` (
`id` int(9) NOT NULL,
`Date` varchar(100) NOT NULL,
`EmpID` varchar(100) NOT NULL,
`name` varchar(100) NOT NULL,
`TeamName` varchar(100) NOT NULL,
`active` varchar(100) NOT NULL,
`idle` double NOT NULL,
`Stime` double NOT NULL,
`Etime` varchar(100) NOT NULL,
`Inofficehr` decimal(20,2) NOT NULL,
`activehr` double(19,2) NOT NULL,
`idlehr` double(19,2) NOT NULL,
`Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=latin1;
为“ id”列设置主键:
ALTER TABLE `dailydata`ADD PRIMARY KEY (`id`);
现在我正在尝试使用以下代码插入数据:
INSERT INTO dailydata
SELECT A.Date, A.EmpID, B.name, B.TeamName,
SUM(CASE WHEN State = 'active' THEN A.MinutesatState ELSE 0 END) AS active,
SUM(CASE WHEN State = 'idle' THEN A.MinutesatState ELSE 0 END) AS idle,
Min(A.Statestarttime) AS Stime, MAX(A.StateEndtime) AS Etime,
ROUND((TIME_TO_SEC(MAX(A.StateEndtime))/60 -
TIME_TO_SEC(MIN(A.StateStarttime))/60)/60,2) as Inofficehr,
ROUND(SUM(CASE WHEN State = 'active' THEN A.MinutesatState ELSE 0 END)/60,2)
AS activehr,
ROUND(SUM(CASE WHEN State = 'idle' THEN A.MinutesatState ELSE 0 END)/60,2)
AS idlehr
FROM time A join ttld.login B on A.EmpID=B.username
WHERE A.Date='01-01-2019' AND A.Statestarttime <>'' AND A.StateEndtime <>''
GROUP BY A.EmpID;
但是我遇到了这个错误:
#1136-列数与第1行的值数不符
我知道我尚未在插入代码中定义ID,其原因是我希望其自动填充。
如何修改我的INSERT
查询代码来做到这一点...
答案 0 :(得分:2)
您的表中有13列,但是您的选择中只有11列,这就是为什么您会收到此错误。
但是首先,要使您的id
列自动填充,您需要将其声明为AUTO_INCREMENT
。您可以使用ALTER TABLE
命令对其进行更改:
ALTER TABLE dailydata CHANGE id id INT AUTO_INCREMENT PRIMARY KEY
由于您的Timestamp
列具有默认值,因此无需为此添加值。
要解决您看到的错误,您需要修改INSERT
查询以匹配要插入数据的列数,方法是
(a)命名您要插入的列;或
(b)为没有值(NULL
和id
)的列插入Timestamp
值
例如(a)
INSERT INTO dailydata (`Date`, `EmpID`, `name`, `TeamName`, `active`, `idle` ,`Stime`, `Etime`, `Inofficehr`, `activehr`, `idlehr`)
SELECT A.Date, A.EmpID, B.name, B.TeamName,
...
例如(b)
INSERT INTO dailydata
SELECT NULL AS id,
A.Date, A.EmpID, B.name, B.TeamName,
...
NULL AS Timestamp
FROM ...