MySQL查询:使用唯一ID更新外键

时间:2018-03-08 06:14:28

标签: mysql subquery unique

我需要将两个表1对1链接,但要比较和链接的值不是唯一的。

我找不到办法。举个例子,我添加了一个非常简单的版本。

CREATE TABLE `T1` (
  `id` int(6) unsigned NOT NULL,
  `cmp` int(3) NOT NULL,
  `uniqueT2Id` int(3) unsigned,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `T2` (
  `id` int(6) unsigned NOT NULL,
  `cmp` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `T1` (`id`, `cmp`, `uniqueT2Id`) VALUES
  ('1', '1', NULL),
  ('2', '1', NULL),
  ('3', '2', NULL),
  ('4', '3', NULL),
  ('5', '1', NULL);

INSERT INTO `T2` (`id`, `cmp`) VALUES
  ('1', '1'),
  ('2', '1'),
  ('3', '1'),
  ('4', '2'),
  ('5', '3');

UPDATE T1 SET uniqueT2Id=
(SELECT id FROM T2 WHERE T2.cmp=T1.cmp AND
  id NOT IN (SELECT * FROM 
               (SELECT uniqueT2Id FROM T1 WHERE uniqueT2Id IS NOT NULL) X) 
 ORDER BY id ASC LIMIT 1);

SELECT * FROM T1;

http://sqlfiddle.com/#!9/3bab7c/2/0

结果是

id  cmp uniqueT2Id
1   1   1
2   1   1
3   2   4
4   3   5
5   1   1

我希望它是

id  rev uniqueT2Id
1   1   1
2   1   2
3   2   4
4   3   5
5   1   3

在UPDATE中,我尝试选择一个尚未使用的ID,但这显然不起作用。有没有人知道在MySQL中这样做的方法,最好没有PHP?

1 个答案:

答案 0 :(得分:0)

我自己找到了一个带有变量的答案。它很可怕,需要在表格中使用虚拟字段,但它有效。我愿意接受改进。

CREATE TABLE `T1` (
  `id` int(6) unsigned NOT NULL,
  `cmp` int(3) NOT NULL,
  `uniqueT2Id` int(3) NULL,
  `dummy` varchar(200) NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `T2` (
  `id` int(6) unsigned NOT NULL,
  `cmp` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `T1` (`id`, `cmp`, `uniqueT2Id`) VALUES
  ('1', '1', NULL),
  ('2', '1', NULL),
  ('3', '2', NULL),
  ('4', '5', NULL),
  ('5', '3', NULL),
  ('6', '1', NULL);

INSERT INTO `T2` (`id`, `cmp`) VALUES
  ('1', '1'),
  ('2', '1'),
  ('3', '1'),
  ('4', '2'),
  ('5', '3');

SET @taken = '/' ;
UPDATE T1 
SET uniqueT2Id= @new:=
  (SELECT id FROM T2 WHERE T2.cmp=T1.cmp AND
    INSTR(@taken, CONCAT('/',id,'/')) = 0
   ORDER BY id ASC LIMIT 1),
  dummy=IF(@new IS NOT NULL,@taken:=CONCAT(@taken, @new, "/"),NULL);

http://sqlfiddle.com/#!9/4a61d/1/0