Jump to content

[SOLVED] mysql query help


will35010

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.