您可以使用纯 SQL 在一条语句中执行此操作(使用合并标签进行更新)。诀窍在于使用一个数字(也称为计数表),它可以在几秒钟内创建和填充(也可以使用一条 SQL 语句)。
这是你的UPDATE
声明
UPDATE table1 t1 JOIN table2 t2
ON t1.id = t2.id JOIN
(
SELECT id, GROUP_CONCAT(DISTINCT tag ORDER BY tag) tags
FROM
(
SELECT a.id, SUBSTRING_INDEX(SUBSTRING_INDEX(tags, ',', n.id), ',', -1) tag
FROM
(
SELECT t1.id, CONCAT(t1.tags, ',', t2.tags) tags
FROM table1 t1 JOIN table2 t2
ON t1.id = t2.id
) a CROSS JOIN tally n
WHERE n.id <= 1 + (LENGTH(tags) - LENGTH(REPLACE(tags, ',', '')))
AND n.id < 100 -- change that number to accommodate max possible number of tags
) b
GROUP BY id
) c ON t1.id = c.id
SET t1.tags = c.tags,
t1.rank = t1.rank + t2.rank
这是用多达 100k 行填充计数表的模式和语句。
CREATE TABLE tally (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
INSERT INTO tally
SELECT NULL
FROM (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
, (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
, (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) c
, (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) d
, (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) e
;
这是SQLFiddle演示