2012-09-24 63 views
-1

什麼是獲得自動增量「counter」的最好方法?它取決於其他字段?自動增量依賴於其他字段

想象一下這個表

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

我需要計數器的值增加1每條記錄我加爲每一位顧客。

問候。

+0

什麼數據庫您使用的? –

+0

標籤爲Firebird的問題。 –

回答

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; 
?> 
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 
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 

看看我們如何使用和與插入增量值而不是更新單個記錄。因此我們可以防止死鎖。

在我們需要通過合併增量記錄清除計數表成一個總價值定期:

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 
+0

我想我沒有正確解釋,對不起,但你的答案會幫助我另一件事。這個想法是,如果我爲表1添加一條新記錄,那麼對於客戶1,計數器值必須是4,但如果是客戶2,計數器值必須是3.這個想法是例如分配一個訂單字段到賬單細節的記錄。賬單的所有細節都在一張表中,而計數器的值必須是每個ID賬單組的自動增量。我希望我現在解釋得更好。謝謝。 – Giu