获得自动增量“计数器”的最佳方法是什么?取决于其他领域?
想象一下这张表
CUSTOMER - COUNTER
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
我为每个客户添加的每条记录都需要计数器增量1。
问候。
答案 0 :(得分:1)
创建附加表以保存每个客户的计数器:
CREATE TABLE customer_counter
(
customer_id INTEGER NOT NULL,
counter INTEGER NOT NULL,
PRIMARY KEY (customer_id)
)
使用以下程序获取给定客户的下一个柜台号码:
CREATE PROCEDURE get_customer_counter (customer_id INTEGER)
RETURNS (counter INTEGER)
AS
BEGIN
SELECT SUM(counter) FROM customer_counter
WHERE customer_id = :customer_id
INTO :counter;
counter = COALESCE(:counter, 0);
EXECUTE STATEMENT
'INSERT INTO customer_counter (customer_id, counter) ' ||
'VALUES (' || :customer_id || ', 1)'
WITH AUTONOMOUS TRANSACTION;
END
了解我们如何使用sum和插入delta值而不是更新单个记录。因此,我们可以防止死锁。
定期我们需要通过将delta记录合并为具有总值的记录来清除计数器表:
CREATE TRIGGER on_disconnect_database
ACTIVE
ON DISCONNECT
AS
DECLARE VARIABLE sm INTEGER;
DECLARE VARIABLE cnt INTEGER;
DECLARE VARIABLE customer_id INTEGER;
BEGIN
FOR
SELECT customer_id, SUM(counter), COUNT(counter)
FROM customer_counter
GROUP BY customer_id
INTO :customer_id, :sm, :cnt
DO BEGIN
IF (:cnt > 1) THEN
BEGIN
DELETE FROM customer_counter WHERE customer_id = :customer_id;
INSERT INTO customer_counter (customer_id, counter)
VALUES (:customer_id, :sm);
WHEN ANY DO
BEGIN
END
END
END
END
答案 1 :(得分:0)
很难真正告诉你对你所提供的内容的确切要求,但我认为你想要遍历每个X字段,它是Y子字段,将它用于计数器或其他任何东西。
<?php
$x = array("customer1","customer2","customer3");
$y = array("name","address","phone");
$counter;
foreach($x as $eachX):
$counter = 1;
foreach($y as $eachY):
//do stuff here
$counter++;
endforeach;
endforeach;
?>
答案 2 :(得分:0)
我认为这个存储过程没问题!
create procedure New_Procedure
returns (
o_customer integer,
o_counter integer)
as
declare variable v_oldcostomer integer;
begin
for select customer
from customers
order by 1
into o_customer
do begin
if (v_oldcostomer is null or (v_oldcostomer is not null and v_oldcostomer <> o_customer) ) then
o_counter = 0;
o_counter = o_counter + 1;
v_oldcostomer = o_customer;
suspend;
end
end