MySQL: aggiungi la colonna sequenza in base a un altro campo
Domanda
Sto lavorando su un codice / database legacy e ho bisogno di aggiungere un campo al database che registrerà un numero di sequenza correlato a quell'ID (esterno).
Dati della tabella di esempio (corrente):
ID ACCOUNT some_other_stuff
1 1 ...
2 1 ...
3 1 ...
4 2 ...
5 2 ...
6 1 ...
Devo aggiungere una colonna sequenziale che aumenta separatamente per ciascun account, ottenendo:
ID ACCOUNT SEQ some_other_stuff
1 1 1 ...
2 1 2 ...
3 1 3 ...
4 2 1 ...
5 2 2 ...
6 1 4 ...
Nota che la sequenza è correlata all'account.
Esiste un modo per raggiungere questo obiettivo in SQL o ricorrere a uno script PHP per fare il lavoro per me?
TIA, Kev
Soluzione
Questo dovrebbe funzionare ma probabilmente è lento:
CREATE temporary table seq ( id int, seq int);
INSERT INTO seq ( id, seq )
SELECT id,
(SELECT count(*) + 1 FROM test c
WHERE c.id < test.id AND c.account = test.account) as seq
FROM test;
UPDATE test INNER join seq ON test.id = seq.id SET test.seq = seq.seq;
Ho chiamato la tabella 'test'; ovviamente questo deve essere impostato correttamente. Devi usare una tabella temporanea perché MySQL non ti permetterà di usare una sottoselezione dalla stessa tabella che stai aggiornando.
Altri suggerimenti
La domanda è taggata come "mysql", quindi sì, l'incremento automatico di MySQL può creare ID sequenziali a livello di gruppo.
vedi http://dev.mysql.com/doc/ refman / 5.0 / it / es-auto-increment.html :
Per le tabelle MyISAM e BDB puoi specificare AUTO_INCREMENT su una colonna secondaria in un indice a più colonne. In questo caso, il valore generato per la colonna AUTO_INCREMENT viene calcolato come MAX (auto_increment_column) + 1 prefisso WHERE = dato-prefisso
. Ciò è utile quando si desidera inserire i dati nei gruppi ordinati.
modifica: esempio di script php (usando PDO , ma è lo stesso gioco con php-mysql modulo)
$pdo = new PDO('mysql:host=...;dbname=...', '...', '...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// example table
$pdo->exec(
'CREATE TEMPORARY TABLE Foo (
id int auto_increment,
account int,
someotherstuff varchar(32),
primary key(account,id)
) engine=MyIsam'
);
// insert example data
$stmt = $pdo->prepare('INSERT INTO Foo (account,someotherstuff) VALUES (?,?)');
$stmt->execute(array(1, '1a'));
$stmt->execute(array(1, '1b'));
$stmt->execute(array(1, '1c'));
$stmt->execute(array(2, '2a'));
$stmt->execute(array(2, '2b'));
$stmt->execute(array(1, '1d'));
unset($stmt);
// query data
foreach( $pdo->query('SELECT account,id,someotherstuff FROM Foo') as $row ) {
echo $row['account'], ' ', $row['id'], ' ', $row['someotherstuff'], "\n";
}
stampe
1 1 1a
1 2 1b
1 3 1c
2 1 2a
2 2 2b
1 4 1d
Crea un trigger:
CREATE TRIGGER trg_mytable_bi
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
DECLARE nseq INT;
SELECT COALESCE(MAX(seq), 0) + 1
INTO nseq
FROM mytable
WHERE account = NEW.account;
SET NEW.seq = nseq;
END;