我正在使用PostgreSQL.
Customer
==================
Customer_ID | Name
Order
==============================
Order_ID | Customer_ID | Price
Run Code Online (Sandbox Code Playgroud)
要插入订单,这是我通常需要做的,
例如,"约翰"放置"1.34"定价订单.
(1) Get Customer_ID from Customer table, where name is "John"
(2) If there are no Customer_ID returned (There is no John), insert "John"
(3) Get Customer_ID from Customer table, where name is "John"
(4) Insert "Customer_ID" and "1.34" into Order table.
Run Code Online (Sandbox Code Playgroud)
这个简单的操作有4个SQL通信与数据库!
有没有更好的方法,可以使用1个SQL语句实现?
Way*_*rad 53
您可以在一个sql语句中为现有客户执行此操作,对于新客户执行3个语句.您所要做的就是乐观主义者,并表现得好像客户已经存在:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Run Code Online (Sandbox Code Playgroud)
如果客户不存在,您将获得一个sql异常,其中的文本将类似于:
null value in column "customer_id" violates not-null constraint
Run Code Online (Sandbox Code Playgroud)
(假设你使customer_id不可为空,我相信你已经这样做了).发生该异常时,将客户插入到customer表中并将插入重做到订单表中:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Run Code Online (Sandbox Code Playgroud)
除非您的业务增长的速度会使"在哪里投入所有资金"成为您唯一真正的问题,否则您的大多数插件都将用于现有客户.因此,大多数情况下,异常不会发生,您将在一个语句中完成.
| 归档时间: |
|
| 查看次数: |
171856 次 |
| 最近记录: |