First of all, make sure your column is name_lindexed. Then you can simply use the sentences ORDER BYand LIMITas follows:
SELECT * FROM personnel ORDER BY name_l, id LIMIT 0, 1;
0 LIMIT, . LIMIT 1, 1, , LIMIT 2, 1 ..
name_l, CREATE INDEX:
CREATE INDEX ix_index_name ON personnel (name_l);
:
CREATE TABLE personnel (
id int not null primary key,
name_l varchar(10),
name_f varchar(10)
);
CREATE INDEX ix_last_name_index ON personnel (name_l);
INSERT INTO personnel VALUES (1, 'Pacino', 'Al');
INSERT INTO personnel VALUES (2, 'Nicholson', 'Jack');
INSERT INTO personnel VALUES (3, 'De Niro', 'Robert');
INSERT INTO personnel VALUES (4, 'Newman', 'Paul');
INSERT INTO personnel VALUES (5, 'Duvall', 'Robert');
:
SELECT * FROM personnel ORDER BY name_l, id LIMIT 0, 1;
+
| id | name_l | name_f |
+
| 3 | De Niro | Robert |
+
1 row in set (0.00 sec)
SELECT * FROM personnel ORDER BY name_l, id LIMIT 1, 1;
+
| id | name_l | name_f |
+
| 5 | Duvall | Robert |
+
1 row in set (0.00 sec)
SELECT * FROM personnel ORDER BY name_l, id LIMIT 2, 1;
+
| id | name_l | name_f |
+
| 4 | Newman | Paul |
+
1 row in set (0.00 sec)
1st UPDATE: ( )
, , , , , , , , .. x x , , , .
, , .
, , . $index = 0 ... LIMIT $index, 1. , $index 1, , $index 1.
, , , ( ), (php). , :
+----+-----------+--------+
| id | name_l | name_f |
+----+-----------+--------+
| 3 | De Niro | Robert |
| 5 | Duvall | Robert |
| 4 | Newman | Paul |
| 2 | Nicholson | Jack |
| 1 | Pacino | Al |
+----+-----------+--------+
, Newman Paul, row=2 , . , , , Newman Paul (row=2). x LIMIT x, 1 row - 1 row + 1 :
SELECT * FROM personnel ORDER BY name_l, id LIMIT 1, 1;
+
| id | name_l | name_f |
+
| 5 | Duvall | Robert |
+
1 row in set (0.00 sec)
SELECT * FROM personnel ORDER BY name_l, id LIMIT 3, 1;
+
| id | name_l | name_f |
+
| 2 | Nicholson | Jack |
+
1 row in set (0.00 sec)
2nd UPDATE:
, MySQL, , . , , , .
, .
:
SELECT p.id, p.name_l, p.name_f, o.record_number
FROM personnel p
JOIN (
SELECT id,
@row := @row + 1 AS record_number
FROM personnel
JOIN (SELECT @row := -1) r
ORDER BY name_l, id
) o ON (o.id = p.id)
WHERE p.name_l = 'Nicholson' AND p.name_f = 'Jack';
:
+----+-----------+--------+---------------+
| id | name_l | name_f | record_number |
+----+-----------+--------+---------------+
| 2 | Nicholson | Jack | 3 |
+----+-----------+--------+---------------+
1 row in set (0.00 sec)
, WHERE p.id = 2, , p.name_l = 'Nicholson' AND p.name_f = 'Jack'.
record_number, 3, , LIMIT 2, 1 LIMIT 4, 1 . :
:
SELECT * FROM personnel ORDER BY name_l, id LIMIT 2, 1;
+
| id | name_l | name_f |
+
| 4 | Newman | Paul |
+
1 row in set (0.00 sec)
:
SELECT * FROM personnel ORDER BY name_l, id LIMIT 4, 1;
+
| id | name_l | name_f |
+
| 1 | Pacino | Al |
+
1 row in set (0.00 sec)