Postgresql - Insert into where not exists using sqlalchemy's INSERT from SELECT
正如这里所指出的,可以使用PostgreSQL 9.1执行以下操作+
1 2 3 4 5 6 7 | INSERT INTO example_table (id, name) SELECT 1, 'John' WHERE NOT EXISTS ( SELECT id FROM example_table WHERE id = 1 ); |
我一直在玩0.9版的sqlacalchemy,在这里他们引入了insert-from-select方法,理论上应该可以处理上述问题。
有可能吗?如果有,怎么办?(因为我想利用在使用原始SQL时未返回的result.inserted_primary_key)
我如何使用bindparams作为"From"select部分的唯一方法是在select中使用表列。
例如
1 2 3 4 5 6 7 8 9 10 | insrt = example_table.insert(). from_select(['id', 'name'], example_table.select(). where(~exists(select([example_table.c.id], example_table.c.id == 1)))) result = session.execute(insrt) if result.is_insert: print 'do something with result.inserted_primary_key' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from sqlalchemy import * """ INSERT INTO example_table (id, name) SELECT 1, 'John' WHERE NOT EXISTS ( SELECT id FROM example_table WHERE id = 1 ); """ m = MetaData() example_table = Table("example_table", m, Column('id', Integer), Column('name', String) ) sel = select([literal("1"), literal("John")]).where( ~exists([example_table.c.id]).where(example_table.c.id == 1) ) ins = example_table.insert().from_select(["id","name"], sel) print(ins) |
输出:
1 2 3 4 | INSERT INTO example_table (id, name) SELECT :param_1 AS anon_1, :param_2 AS anon_2 WHERE NOT (EXISTS (SELECT example_table.id FROM example_table WHERE example_table.id = :id_1)) |