【问题标题】:MySQL conditional table update Unknown Column error 1054MySQL条件表更新未知列错误1054
【发布时间】:2016-07-12 16:24:22
【问题描述】:

我有两张桌子:

  • Table_A = 存储结果
  • Table_B = 用于聚合函数

Table_ATable_B 共享两个名为 IDCYCLE 的列,但 Table_B 包含多次出现的 CYCLE。我想计算CYCLETable_B 中出现的次数并将它们存储在Table_A 中。例如,如果CYCLE = 42 我们有 20 行具有相同的值,我想计算它(即 20)并将其存储在CYCLE 下的Table_A 中,因为CYCLE 将具有相同的值(42) 但是Table_A 中的COUNT 列中的CYCLE 将包含20。这是我到目前为止所拥有的:

UPDATE database.Table_A
SET count =
(
SELECT ID, CYCLE,
COUNT(*) FROM database.Table_2
GROUP BY ID, CYCLE
)
WHERE database.Table_1.ID = database.Table_2.ID AND
      database.Table_1.CYCLE = database.Table_2.CYCLE

我不断收到Error Code: 1241. Operand should contain 1 column(s)

对我的查询有什么建议吗?

编辑 1

SELECT 语句返回两列。这就是导致Error Code: 1241 的原因,但现在解决了,我得到Error Code: 1054. Unknown column 'database.Table_2.CYCLE' in 'where clause'

【问题讨论】:

  • @Drew 感谢您指出这一点。我了解SELECT 语句的问题出在哪里,并已编辑我的问题以反映这一点。现在我面临Unknown column... - 错误1054。
  • 您不能使用另一个表中的数据更新一个表,您需要使用 JOIN 来更新。 database.Table_2.CYCLE = database.Table_2.CYCLE 是什么?你的意思是database.Table_1.CYCLE = database.Table_2.CYCLE 吗?我假设你的意思是 mysql 的问题
  • @AbhikChakraborty 是的,我也更新了。您是否建议在UPDATE 语句之后使用INNER JOIN
  • 不确定 Table_1 和 Table_2 来自哪里,但是假设表名如问题的第一部分所示,即Table_ATable_B 这个查询应该可以工作update Table_A a join ( SELECT ID, CYCLE, COUNT(*) as cnt FROM Table_B GROUP BY ID, CYCLE )b on b.ID = a.ID and b.CYCLE = a.CYCLE set a.count` = b .cnt;`

标签: mysql sql


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

如果它打扰到我的同龄人,我会很乐意删除它。事实上我今天不能删除它,因为我已经用完了所有的选票。

【讨论】:

  • 请在你的回答中添加与问题相关的查询,以便他接受:)
  • 好的,几分钟后就可以了。如果我对他的架构有所了解。
猜你喜欢
  • 2016-04-01
  • 2012-03-09
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
相关资源
最近更新 更多