使用自动INSERT进行Sql UPDATE

时间:2016-05-26 08:46:47

标签: sql postgresql sql-update sql-insert

我有这样的设置

CREATE TABLE Mother (
   id SERIAL PRIMARY KEY
);

CREATE TABLE Kitten (
   id SERIAL PRIMARY KEY AUTO_INCREMENT,
   mother_id INTEGER NULL REFERENCES Mother
);

小猫表已经填满,其中一些表格中有一位母亲,但有些人没有。表格可能如下所示:

== Mother ==
| 1 |
| 2 |

== Kitten ==
| 1 | NULL |
| 2 |    1 |
| 3 | NULL |
| 4 |    2 |
| 5 |    1 |
| 6 | NULL |

现在(由于一些要求的变化)每个小猫必须有一个应该只是被创建的母亲。我尝试了以下无法正常工作

UPDATE Kitten
SET mother_id = (
  INSERT INTO Mother DEFAULT VALUES RETURNING id
)
WHERE mother_id IS NULL;

错误是

Fehler in der SQL-Abfrage: ERROR: syntax error at or near "INTO"
LINE 3: INSERT INTO Mother DEFAULT VALUES RETURNING id

使用PosgreSQL 9.3.5

自动增量 - 注释:" serial"的组合和"主键"默认情况下启用自动增量

这是剪辑的sql,用于创建描述的数据库状态:

drop table if exists Kitten;
drop table if exists Mother;

CREATE TABLE Mother (
  id SERIAL PRIMARY KEY
);

CREATE TABLE Kitten (
  id SERIAL PRIMARY KEY,
  mother_id INTEGER NULL REFERENCES Mother
);

insert into Mother default values;
insert into Mother default values;

insert into Kitten (mother_id) values (NULL);
insert into Kitten (mother_id) values (1);
insert into Kitten (mother_id) values (NULL);
insert into Kitten (mother_id) values (2);
INSERT INTO Kitten (mother_id) VALUES (1);
INSERT INTO Kitten (mother_id) VALUES (NULL);

2 个答案:

答案 0 :(得分:1)

如果每只孤儿小猫需要一位母亲,您可以执行以下操作:

var building = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(-1.679800, 51.997300, 180.75),
    model: {
                uri: '/models/myBuilding.glb',
                minimumPixelSize: 64
            }
        });

答案 1 :(得分:0)

我发现了一个适合我的纯SQL解决方案。它在母方使用临时列。

-- prepare situation (same like in the question)
DROP TABLE IF EXISTS Kitten; DROP TABLE IF EXISTS Mother;
CREATE TABLE Mother (id SERIAL PRIMARY KEY);
CREATE TABLE Kitten (id SERIAL PRIMARY KEY,mother_id INTEGER NULL REFERENCES Mother);
INSERT INTO Mother DEFAULT VALUES;INSERT INTO Mother DEFAULT VALUES;
INSERT INTO Kitten (mother_id) VALUES (NULL);INSERT INTO Kitten (mother_id) VALUES (1);INSERT INTO Kitten (mother_id) VALUES (NULL);INSERT INTO Kitten (mother_id) VALUES (2);INSERT INTO Kitten (mother_id) VALUES (1);INSERT INTO Kitten (mother_id) VALUES (NULL);

-- create temporarily "bidirectionality"
-- by creating a reference from mother to kitten
ALTER TABLE mother ADD kitten_id INTEGER;

-- create new Mothers for motherless kittens with reference to this kitten
INSERT INTO mother (kitten_id)
  (SELECT id FROM kitten WHERE mother_id IS NULL);

-- update kittens 
UPDATE kitten SET mother_id =
  (SELECT id FROM mother WHERE mother.kitten_id = kitten.id)
WHERE mother_id IS NULL;

-- remove temporary column
ALTER TABLE mother DROP kitten_id;

-- make sure this never happens again
ALTER TABLE kitten ALTER mother_id SET NOT NULL;

-- show results
SELECT kitten.id AS Kitten_Id , mother.id AS Mother_Id FROM kitten, mother WHERE kitten.mother_id = mother.id ORDER BY Kitten_id