Results 1 to 2 of 2

Thread: How to find a n'th record from a selection?

  1. #1
    Join Date
    Sep 2004
    Posts
    3

    How to find a n'th record from a selection?

    Table 'persons_cars' with 3 columns:

    ------------------------
       id | person_id |& nbsp; car
    ------------------------
        1 |      111    | Toyo ta
        3 |      111    | Mits ubishi
        4 |      222    | Mazd a
        7 |      222    | Toyo ta
        9 |      111    | Niss an
      11 |    &nbsp ;333    | BMW
      12 |    &nbsp ;444    | Toyota
      13 |    &nbsp ;444    | Volvo
      16 |    &nbsp ;111    | BMW
      22 |    &nbsp ;111    | GMC
      29 |    &nbsp ;333    | Honda
    ------------------------

    How to find a nth record (according to 'id') from the selection of a specific person?

    For example, I have to find a 4th record of the selection where person id=111. Right answer is is the record with id=16.
    [SELECT * FROM persons_cars WHERE person_id=111 ORDER BY id; 4th record from that set is with id=16, person_id=111, car=BMW]

    Value n is an input and can vary.

  2. #2
    Join Date
    Feb 2005
    Posts
    1

    Thumbs up

    CREATE TEMPORARY TABLE tmptable
    SELECT id , person_id, car
    FROM persons_cars
    WHERE person_id = 111
    LIMIT 3,1;

    DELETE FROM persons_cars USING tmptable, persons_cars
    WHERE persons_cars.id = tmptable.id;

    That took me a little while to figure out, so I hope you're happy, jackass! . Unfortuneatly,MySQL doesn't take too kindly to delete subqueries; it'd be easier to do it that way, if it could be done. I'm not saying it can't be done that way... just I couldn't figure out how to do it that way.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •