-1

获得取决于其他领域的自动增量“计数器”的最佳方法是什么?

想象一下这张桌子

CUSTOMER - COUNTER
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2

我需要 Counter 为每个客户添加的每条记录增加 1。

问候。

4

3 回答 3

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 值而不是更新单个记录。因此,我们防止了死锁。

定期我们需要通过将增量记录合并为一个总值来清除计数器表:

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
于 2012-09-24T09:40:26.533 回答
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;
?>
于 2012-09-24T08:59:11.247 回答
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
于 2012-09-24T09:33:37.797 回答