简体   繁体   中英

Order SELECT Statement from joined tables by variable

I am trying to order my query results by a variable created from a date calculation from the database..

I have a row in my db called "DateInStock" which is a VARCHAR and inputted from a csv file like so - 9/9/2015

$result = mysql_query("SELECT * FROM csv INNER JOIN kbb ON csv.VIN=kbb.Vin ORDER BY $numberDays DESC");
while($row = mysql_fetch_array( $result )) {

// Calculate Days in Stock
$todaydate = date("m/d/Y");
$dis = $row['DateInStock'];
$startTimeStamp = strtotime($todaydate);
$endTimeStamp = strtotime($dis);
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400;  // 86400 seconds in one day
$numberDays = intval($numberDays);

echo $numberDays;
}

So $numberDays gives me the number of days its been in stock..

echo $numberdays; // Gives me 40, 38, 30 etc.. for each iteration 

I would like to order the query results by $numberDays either DESC or ASC

It would be much more efficiently to use date/timestamp data type for your 'DateInStock' column. But you can convert it to the date data type on the fly:

create table aaa(dt varchar(30));

insert into aaa values
('2015-12-01'),('2016-01-01'),('2016-01-10'),('2016-01-20');

SQL:

select datediff(cast(dt as date), now()) as diff from aaa;

Output:

diff
-62
-31
-22
-12

Here is SQLFiddle

Ok Thanks to @LordBaconPants this did it -

$result = mysql_query("SELECT * FROM csv INNER JOIN kbb ON csv.VIN=kbb.Vin ORDER BY STR_TO_DATE(DateInStock, '%m/%d/%Y') DESC ");

That fixes the issue of the date in the db but still need to know how to use a calculated variable to sort the query so I may be back.. Thanks all!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM