Mysql Full Outer加入临时表

时间:2012-06-12 09:04:15

标签: mysql join temp-tables

关于mysql(5.1.36)中的完全加入存在很多问题。当然,解决方案是join-union组合。

我的问题是我有两个临时表,如下所示:

CREATE TEMPORARY TABLE wConfs
(
    idWorker INT,
    confs SMALLINT
) ENGINE=INNODB;

CREATE TEMPORARY TABLE wRejects
(
    idWorker INT,
    rejects SMALLINT
) ENGINE=INNODB;

JOIN-UNION mix不能用于完全连接临时表,因为它会产生ERROR 1137 (HY000): Can't reopen table

我的问题是 - 在临时表上实现完全连接的最佳性能最简单的解决方案是什么?

修改: JOIN-UNION混合:

SELECT wc.idWorker, wc.confs, wr.rejects FROM wConfs wc LEFT JOIN wRejects wr 
ON (wr.idWorker = wc.idWorker)
UNION
SELECT wc.idWorker, wc.confs, wr.rejects FROM wConfs wc RIGHT JOIN wRejects wr 
ON (wr.idWorker = wc.idWorker);

2 个答案:

答案 0 :(得分:5)

尝试从两个表创建具有不同idWorker值的第三个临时表,然后在JOIN-UNION混合中使用它,例如 -

CREATE TEMPORARY TABLE all_id
  SELECT idWorker FROM wConfs UNION SELECT idWorker FROM wRejects;

SELECT t.idWorker, c.confs, r.rejects FROM all_id t
LEFT JOIN wConfs c
  ON t.idWorker = c.idWorker
LEFT JOIN wRejects r
  ON t.idWorker = r.idWorker;

答案 1 :(得分:1)

我找到了解决问题的另一种方法。我还创建了第3个临时表:

DROP TABLE IF EXISTS wResults;
CREATE TEMPORARY TABLE wResults
(
    idWorker INT PRIMARY KEY,
    rejects SMALLINT,
    confs SMALLINT
) ENGINE=INNODB;

现在我像这样插入行:

INSERT INTO wResults(idWorker, confs)
    SELECT idWorker, confs FROM wConfs;

INSERT INTO wResults(idWorker, rejects)
    SELECT wr.idWorker, wr.rejects FROM wRejects wr
    ON DUPLICATE KEY UPDATE rejects = wr.rejects;

它就像一个魅力。我想如果要插入大量数据 - 它会很慢,但我的表格相当小。 无论如何,谢谢大家!