我的MySQL数据库中没有任何索引或主键。我无法更改表的架构(它不是“我的”表)。由于表存储以间隔到达的数据,因此可能存在重复。
例如:
+--------------+--------------+--------+----------+----------+---------+ | first_seen | last_seen | type | name | hitcnt | data | +--------------+--------------+--------+----------+----------+---------+ | 15:12:02 | 16:02:32 | 5 | foo | 3 | difank | +--------------+--------------+--------+----------+----------+---------+ | 19:52:23 | 22:06:20 | 5 | foo | 4 | difank | +--------------+--------------+--------+----------+----------+---------+
现在我想把它“减少”为:
+--------------+--------------+--------+----------+----------+---------+ | first_seen | last_seen | type | name | hitcnt | data | +--------------+--------------+--------+----------+----------+---------+ | 15:12:02 | 22:06:20 | 5 | foo | 7 | difank | +--------------+--------------+--------+----------+----------+---------+
如果可能的话,我想“就地”(即就地)这样做。
使用GROUP BY
,MIN()
,MAX()
等。我可以编写一个完全返回我想要的内容的查询:
SELECT
MIN(first_seen),
MAX(last_seen),
type,
name,
SUM(hitcnt) as hit,
data
FROM <table>
GROUP BY type, name, data
ORDER BY hit desc, type;
问题是:我如何使用该查询的结果(有效地)替换现有数据?
SELECT INTO
)?
答案 0 :(得分:0)
TRUNCATE TABLE table_name;
INSERT INTO table_name (column1.....)
SELECT
MIN(first_seen),
MAX(last_seen),
type,
name,
SUM(hitcnt) as hit,
data
FROM <table>
GROUP BY type, name, data
ORDER BY hit desc, type;
确保插入的列数和选择标记匹配。
答案 1 :(得分:0)
我最终使用了以下方法:
CREATE TABLE tmp_table IF NOT EXISTS AS (SELECT ...);
然后移动&#34; new&#34;使用ALTER TABLE ... RENAME ...;
后跟旧{原始表的DROP TABLE ...;
。
这似乎有效。