【问题标题】:Insert value into specific column from another table with groupby使用 groupby 将值插入另一个表中的特定列
【发布时间】:2015-09-19 16:02:18
【问题描述】:

我正在使用 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);";

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

【问题讨论】:

  • 这是一个更新连接模式,或者至少是一个更新 stmt。不是插入。你可以做一个 upsert,但我不会去那里
  • 好的,很好的线索。我会找到解决办法的。 (但是,我需要这里的解决方案)

标签: mysql datetime insert where


【解决方案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 被触摸。

【讨论】:

  • 很好,选中绿色标记为已回答。还有你刚才问的other one
  • 你在我回答的左上角数字 0 下把它变成了一个绿色的复选标记。谢谢你,先生。快乐的小径:)
  • 随时知道在哪里可以找到我们:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2022-01-24
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多