tags:

views:

51

answers:

2

Hi everyone,

I have a table with details on personnel. I would like to create a Next/Previous link based on the individual's last name. Since personnel were not added in alphabetical order, selecting the next or previous row based on its ID does not work.

It is a hefty table - the pertinent fields are id, name_l, and name_f. I would like to order by name_l, the individuals' last name.

How would I go about accomplishing this task?

Thanks!

Edit This will be used on a Personnel Details page, the result will generate links to the next/prev entry in the database (ordered by last name) based on the current row. For example, if I am viewing Joe Hammer, the Next link would link to Frank Ingram.

Final code

Thanks to Daniel, here is what I finally got to work:

First, I set an increment at 0: $i = 0. Then, while looping through records with a while loop, I increased this by 1 = $i++. I then made a link to the details page for that particular entry:

<a href="details.php?id=<?php echo $member['id'];?>&amp;row=<?php echo $i;?>">Details</a>

On the Details page, I used the following SQL to select the next record:

$row = $_GET['row'];
$getNext = mysql_query("SELECT * FROM members ORDER BY name_l, id LIMIT ".$row.", 1");
$next = mysql_fetch_assoc($getNext);
$nextLink = $row + 1;

Finally, the link:

<a href="member_details.php?id=<?php echo $next['id'];?>&amp;row=<?php echo $nextLink;?>"><?php echo $next['name_l'] . ", " . $next['name_f'];?></a>
A: 

Try a better SQL SELECT statement:

SELECT * FROM tblPersonnel ORDER BY name_l ASC

Try this link for more info: http://w3schools.com/sql/sql_orderby.asp

Jeff
+4  A: 

First of all, make sure that your name_l column is indexed. Then you can simply use the ORDER BY and the LIMIT clauses as follows:

SELECT * FROM personnel ORDER BY name_l, id LIMIT 0, 1;

Simply increment the 0 value in the LIMIT clause to select the next record within the ordered set. Therefore use LIMIT 1, 1 to get the second record, LIMIT 2, 1 for the third, etc.

To create an index on name_l you can use the CREATE INDEX command:

CREATE INDEX ix_index_name ON personnel (name_l);

Test case:

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');

Results:

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: (Further to the comments below)

The above example is suitable mainly if you start by displaying the first record, and then you move sequentially to next, and maybe next again, and perhaps one back, etc. You could also easily move x steps forward and x steps backwards, but this does not appear to be required.

If you start from a random record however, it will be more difficult to adapt the query above to get the next and previous records.

If this is the case, then you can simply keep an index counter of where you currently stand. You start with $index = 0, and display the first record by using ... LIMIT $index, 1. Then you display the next by incrementing $index by 1, and you display the previous by decrementing $index by 1.

If on the other hand, you will be rendering the personnel list, and then the user will click on one record (at random), you could also make this work with some help from the applications-side (php). Let's say you render the following ordered list to the user:

+----+-----------+--------+
| id | name_l    | name_f |
+----+-----------+--------+  // [Hidden info]
|  3 | De Niro   | Robert |  // Row 0 
|  5 | Duvall    | Robert |  // Row 1
|  4 | Newman    | Paul   |  // Row 2
|  2 | Nicholson | Jack   |  // Row 3
|  1 | Pacino    | Al     |  // Row 4
+----+-----------+--------+

Now if the user clicks on Newman Paul, you would have to pass the row=2 parameter to the page that will display the details of this employee. The page that renders the details of the employee now knows that Newman Paul is the 3rd row (row=2). Therefore to get the previous and the next records you would simply change the x in LIMIT x, 1 by row - 1 for the previous record and row + 1 for the next:

-- Previous 
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)


-- Next 
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:

You can use the following MySQL-specific query to get the record number within the ordered list of any random employee, which then can be used to get the previous and next records. Note however that this is not very efficient, and may degrade performance if you have thousands of records.

Let's say you are in employee Nicholson Jack.

You could do the following query:

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

Which returns this:

+----+-----------+--------+---------------+
| id | name_l    | name_f | record_number |
+----+-----------+--------+---------------+
|  2 | Nicholson | Jack   |             3 |
+----+-----------+--------+---------------+
1 row in set (0.00 sec)

Note that in the WHERE clause you could have used p.id = 2 if the id is known, instead of p.name_l = 'Nicholson' AND p.name_f = 'Jack'.

Now we can use the record_number field, which is 3 in this case, to get the previous and the next records, simply by using the original query from the top of this answer, and replacing LIMIT 2, 1 for the previous and LIMIT 4, 1 for the next. There you go:

The previous of Nicholson Jack:

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)

The next from Nicholson Jack:

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)
Daniel Vassallo
Okay, I created an index on name_l. Please see my edit to get a better idea of what I'm trying to accomplish. Thanks! :)
NightMICU
@NightMICU: Please check my update answer. Does this example help you?
Daniel Vassallo
Shucks, I thought this was the solution until I tested a little bit further. :( Using this SELECT statement I was able to retrieve the next row (but not in the correct order, explained next):"SELECT * FROM personnel ORDER BY name_l, id LIMIT ".$id.", 1". It appears this works only if the entries were entered in alphabetical order and only seems to work for retrieving the next entry, not the previous. Am I perhaps missing something? Or perhaps not explaining very well? Thanks so much for your time, Daniel
NightMICU
Another quick note - this is on a page that ONLY displays the results of one query. For example, let's say we're viewing Joe Hammer with a row ID of 3. The next individual is Frank Ingram with a row ID of 10.
NightMICU
@NightMICU: What does the php `$id` variable contain? In that place it was intended to have a sort of "row number" starting from 0, such that you would have `LIMIT 0, 1` to get the first record, `LIMIT 1, 1` to get the second record, `LIMIT 2, 1` to get the third, etc. The order in which they were inserted shouldn't matter if you use this approach (if this is possible within your application after all)
Daniel Vassallo
@NightMICU: Ok, I think I understand your problem... let me update my answer with some tips on this.
Daniel Vassallo
Okay, the above looks really promising. The primary index for this table is ID, an auto-increment INT field. Since new people can be added to the table (or removed) at any time, the ID does not correlate to the last name (for example, Sam Abbott might have an ID of 30). Basically, you're saying that I need to tell the page that displays the record what row number it is in my table? If so, how would I go about obtaining that number? Really can't thank you enough for your patience and assistance.
NightMICU
@NightMICU: No probs... Actually you don't have to tell the page that displays the employee details the "row number" within the table, but the record number of when the list is ordered. Consider the test case in my answer. The records where inserted with a sequential ID (as if it was auto increment), and they were not inserted in alphabetical order by last name. Note that the hidden `Row` column I showed in the updated part under the heading `// [Hidden info]` is different from the `id` and from the order of insertion...
Daniel Vassallo
... What I was suggesting, is that if you are first displaying the ordered list from php, and then allowing the user to click on one record, you could obtain that "record number" from php, simply by counting the rows as you are processing them from MySQL one by one... However, let me do another small update, as I think there is a way to get this "record number" without having to go through all this.
Daniel Vassallo
@NightMICU: Please check the latest update. This assumes that you start from a random employee, in this case 'Nicholson Jack', and shows you how to do a query that gets you a `record_number` field, which you can increment or decrement by 1 to substitute for `x` in the `LIMIT x, 1` part of the original query.
Daniel Vassallo
Thanks so much, Daniel. See my update in the original question for what ended up working pretty well (from what I can tell so far), thanks to your solution and some ol' PHP basics.
NightMICU
@NightMICU: Yes, thats good. That solution should scale better than the suggestion I gave in the last update, because the database wouldn't have to calculate the `record_number` each time in the details page. It is already provided as a parameter... which is good. Glad it works now :)
Daniel Vassallo