使用groupby将值插入另一个表的特定列

时间:2015-09-19 16:02:18

标签: mysql datetime insert where

我正在使用MySQL。我想将来自datetime的groupby的值的结果插入到特定列(使用where,也许)。让我们说: 我有两张桌子(a,b)。在表a中,我想获得一小时内总记录数(我有datetime列),然后结果将插入到表b中,但是在特定ID中(已经存在ID的值)。

这是我的错误代码:

INSERT INTO b(value)
WHERE ID=15
SELECT DAY COUNT(*)
FROM a
WHERE date >= '2015-09-19 00:00:00' AND date < '2015-09-19 00:59:59'
GROUP BY DAY(date),HOUR(date);";

我可以从这个案例中查询吗? 非常感谢您的回复!

1 个答案:

答案 0 :(得分:1)

模式

create table tA
(   id int auto_increment primary key,
    theDate datetime not null,
    -- other stuff
    key(theDate) -- make it snappy fast
);

create table tB
(   myId int primary key,   -- by definition PK is not null
    someCol int not null
);

-- truncate table tA;
-- truncate table tB;

insert tA(theDate) values
('2015-09-19'),
('2015-09-19 00:24:21'),
('2015-09-19 07:24:21'),
('2015-09-20 00:00:00');

insert tB(myId,someCol) values (15,-1); --    (-1) just for the heck of it
insert tB(myId,someCol) values (16,-1); --    (-1) just for the heck of it

查询

update tB
set someCol=(select count(*) from tA where theDate between '2015-09-19 00:00:00' and '2015-09-19 00:59:59')
where tB.myId=15;

结果

select * from tB;
+------+---------+
| myId | someCol |
+------+---------+
|   15 |       2 |
|   16 |      -1 |
+------+---------+

仅触及myId = 15.