使用SQLAlchemy的条件Oracle SQL ALL语句

gxwragnw  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(81)

同事们!
有一个问题我找不到答案
是否可以使用SQLAlchemy 1.4按条件插入到多个表中,同时进行单个选择查询?对以下查询语法(ORACLE)感兴趣:

INSERT [ ALL | FIRST ]
    WHEN condition1 THEN
        INTO table_1 (column_list ) VALUES (value_list)
    WHEN condition2 THEN 
        INTO table_2(column_list ) VALUES (value_list)
    ELSE
        INTO table_3(column_list ) VALUES (value_list)
Subquery

目前,我所能想到的就是执行一个子查询,并使用if..elif..对其结果进行查询。
但是这种方法在速度和内存消耗上明显输给了上面的查询。
如果有人对这个问题有任何想法,请分享。谢谢你,谢谢

yr9zkbsy

yr9zkbsy1#

在Oracle中,如果您有表:

CREATE TABLE table_1 (id NUMBER, a NUMBER);
CREATE TABLE table_2 (id NUMBER, b NUMBER, c NUMBER);
CREATE TABLE table_3 (id NUMBER, a NUMBER, c NUMBER);

然后你可以使用查询:

INSERT ALL
  WHEN a < 5 THEN
    INTO table_1 (id, a) VALUES (id, a)
  WHEN a >= 3 AND a < 7 THEN
    INTO table_2 (id, b, c) VALUES (id, b, c)
  WHEN a >= 4 AND a < 8 THEN
    INTO table_3 (id, a, c) VALUES (id, a, c)
SELECT 1 As id, 1 AS a, 1 AS b, 1 AS c FROM DUAL UNION ALL
SELECT 2, 2, 2, 2 FROM DUAL UNION ALL
SELECT 3, 3, 3, 3 FROM DUAL UNION ALL
SELECT 4, 4, 4, 4 FROM DUAL UNION ALL
SELECT 5, 5, 5, 5 FROM DUAL UNION ALL
SELECT 6, 6, 6, 6 FROM DUAL UNION ALL
SELECT 7, 7, 7, 7 FROM DUAL UNION ALL
SELECT 8, 8, 8, 8 FROM DUAL;

然后,表格包含:

SELECT * FROM table_1

| ID|一|
| --|--|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |

SELECT * FROM table_2

| ID| B| C|
| --|--|--|
| 3 | 3 | 3 |
| 4 | 4 | 4 |
| 5 | 5 | 5 |
| 6 | 6 | 6 |

SELECT * FROM table_3

| ID|一|C|
| --|--|--|
| 4 | 4 | 4 |
| 5 | 5 | 5 |
| 6 | 6 | 6 |
| 7 | 7 | 7 |
fiddle
是否可以使用SQLAlchemy 1.4按条件插入到多个表中,同时进行单个select INSERT查询?
直接执行SQL即可。参见How to execute raw SQL in Flask-SQLAlchemy app,它适用于用户定义的SELECTINSERTUPDATEDELETE语句。

your_sql = """INSERT ALL
  WHEN a < 5 THEN
    INTO table_1 (id, a) VALUES (id, a)
  WHEN a >= 3 AND a < 7 THEN
    INTO table_2 (id, b, c) VALUES (id, b, c)
  WHEN a >= 4 AND a < 8 THEN
    INTO table_3 (id, a, c) VALUES (id, a, c)
SELECT 1 As id, 1 AS a, 1 AS b, 1 AS c FROM DUAL UNION ALL
SELECT 2, 2, 2, 2 FROM DUAL UNION ALL
SELECT 3, 3, 3, 3 FROM DUAL UNION ALL
SELECT 4, 4, 4, 4 FROM DUAL UNION ALL
SELECT 5, 5, 5, 5 FROM DUAL UNION ALL
SELECT 6, 6, 6, 6 FROM DUAL UNION ALL
SELECT 7, 7, 7, 7 FROM DUAL UNION ALL
SELECT 8, 8, 8, 8 FROM DUAL"""

db.engine.execute(text(your_sql)).execution_options(autocommit=True))

相关问题