我正在使用 PostgreSQL。
Customer
==================
Customer_ID | Name
Order
==============================
Order_ID | Customer_ID | Price
要插入订单,这是我通常需要做的,
例如,“John”下了“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.
这个简单的操作涉及到4条与数据库的SQL通信!
有没有更好的方法,可以使用 1 个 SQL 语句来实现?
对于现有客户,您可以使用 1 个 sql 语句来完成此操作,对于新客户,您可以使用 3 个语句来完成此操作。您所要做的就是保持乐观并表现得好像客户已经存在一样:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
如果客户不存在,您将收到一个 sql 异常,其文本类似于:
null value in column "customer_id" violates not-null constraint
(假设您将 customer_id 设置为不可空,我确信您做到了)。发生异常时,将客户插入客户表中,然后重做插入订单表中的操作:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
除非您的业务增长速度使“所有钱都花在哪里”成为您唯一真正的问题,否则您的大部分插入内容将是针对现有客户的。因此,大多数时候,异常不会发生,您只需一条语句即可完成。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)