sql >> Database teknologi >  >> RDS >> Mysql

Hvordan kan jeg med MySQL generere en kolonne, der indeholder postindekset i en tabel?

Du kan prøve følgende:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r;
 

JOIN (SELECT @curRow := 0) del tillader den variable initialisering uden at kræve et separat SET kommando.

Testtilfælde:

CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);
 

Testforespørgsel:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r
WHERE   l.score > 50;
 

Resultat:

+----------+----------+-------+------------+ | position | username | score | row_number | +----------+----------+-------+------------+ | 3 | c | 75 | 1 | | 5 | e | 55 | 2 | | 6 | f | 80 | 3 | +----------+----------+-------+------------+ 3 rows in set (0.00 sec)

  1. SQL-forespørgselskolonnen findes ikke fejl

  2. Skift en eksisterende kolonne til en beregnet kolonne i SQL Server (T-SQL-eksempel)

  3. Sekvens vs identitet

  4. Sådan finder du en databases ANSI_NULLS-indstilling i SQL Server (T-SQL)