1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

SQL query for next and previous record?

Discussion in 'MySQL' started by Kaizoku, Jan 26, 2008.

  1. #1
    My database structure is like this:

    
    [id]	[cat]	  [episode]		[time]
     4	  1		01		timestamp
     2	  1		02		timestamp
     8	  1	     03 04		timestamp
     3	  1	 	05		timestamp
     5	  2		01		timestamp
     6	  2		02		timestamp
     1	  2		03		timestamp
     7	  2	     Movie		timestamp
    
    Code (markup):
    My current sql is like this
    
    SELECT * FROM `table` WHERE `cat`='1' AND `episode`='02' ORDER BY `episode`
    
    Code (markup):
    How would I select the previous episode(01) and next episode(03 04) as well?
     
    Kaizoku, Jan 26, 2008 IP
  2. Kuldeep1952

    Kuldeep1952 Active Member

    Messages:
    290
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    60
    #2
    If you want separate queries, then this could work
    For previous episode(01)

    SELECT * FROM `table` WHERE `cat`='1' AND `episode`< '02' ORDER BY `episode` DESC LIMIT 1

    For next episode(03 04)

    SELECT * FROM `table` WHERE `cat`='1' AND `episode`> '02' ORDER BY `episode` LIMIT 1
     
    Kuldeep1952, Jan 26, 2008 IP
  3. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #3
    As you can see the episodes are not all integers, so it won't work.
     
    Kaizoku, Jan 26, 2008 IP
  4. adams2on

    adams2on Peon

    Messages:
    30
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I think you need to restructure the episode data, or else (simpler) add a new column ('episode_order') with only integers in it corresponding to the desired order of the episodes. Then in the above queries, replace 'episode'<'02' with 'episode_order' < n (where n = episode_order value corresponding to '02'), and 'episode'>'02' with 'episode_order' < n. If you need all 3 rows from the same single query, then your SQL gets more complicated. Do you need it that way?
     
    adams2on, Jan 27, 2008 IP
    Kaizoku likes this.
  5. adams2on

    adams2on Peon

    Messages:
    30
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Oops - sorry - second replacement should be 'episode_order' > n.
     
    adams2on, Jan 27, 2008 IP
  6. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #6
    Ah I see, thank you for the suggestion, never thought of that way, thanks rep added :)
     
    Kaizoku, Jan 27, 2008 IP