Jump to content

Recommended Posts

I have a table to store fuel info. I want to retrieve the last two records entered to calculate miles-per-gallon.

 

Here's my table:

-- Table structure for table `fuel`
--

CREATE TABLE IF NOT EXISTS `fuel` (
  `vin` varchar(20) NOT NULL,
  `mileage` mediumint(9) NOT NULL,
  `gallons` float NOT NULL,
  `total` float NOT NULL,
  `date` date NOT NULL,
  `driver` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

I have this query but I don't know how to retrieve just the last two records. Or is there a better way to calculate it?

 

SELECT mileage, gallons FROM fuel WHERE vin = '$vin'

Link to comment
https://forums.phpfreaks.com/topic/161114-solved-mysql-query-help/
Share on other sites

When you say just the last two records you mean for example you have 10 rows in the database and you want to retrieve miles and gallons for entry 9 and 10?

 

Correct. I just want to make sure that it will actually be the last two records. For instance if record 2 was edited, would it's number now become 10 since it was the last one edited? I only want to retrieve the last two records entered.

Assuming 'date' is the date when you inserted the record, you can use that to order.

 

ORDER BY `date` DESC LIMIT 2

 

I thought about that but I thought I would have to do that from the php side and was trying to avoid that. I didn't know you could do it from the mysql side. Thanks!!!

Assuming 'date' is the date when you inserted the record, you can use that to order.

 

ORDER BY `date` DESC LIMIT 2

 

I thought about that but I thought I would have to do that from the php side and was trying to avoid that. I didn't know you could do it from the mysql side. Thanks!!!

 

In this case PHP would have nothing to do with the query except for retrieving the desired vin #.  The final query should look something similar to:

 

SELECT mileage, gallons FROM fuel WHERE vin = '$vin' ORDER BY `date` DESC LIMIT 2;

 

NOTE - If this problem is completely resolved then you should mark it so by clicking the "Topic Solved" button in the bottom left right above "Quick Reply".

 

Good luck.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.