[英]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 我的数据库中有一行名为“ DateInStock”的行,该行是VARCHAR,是从csv文件中输入的,就像这样-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.. 因此,$ numberDays给了我存货的天数。
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 我想按$ numberDays或DESC或ASC排序查询结果
It would be much more efficiently to use date/timestamp data type for your 'DateInStock' column. 在“ DateInStock”列中使用日期/时间戳数据类型会更有效。 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: SQL:
select datediff(cast(dt as date), now()) as diff from aaa;
Output: 输出:
diff
-62
-31
-22
-12
Ok Thanks to @LordBaconPants this did it - 好吧,感谢@LordBaconPants做到了-
$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! 这解决了数据库中日期的问题,但仍然需要知道如何使用计算出的变量对查询进行排序,因此我可能会回来..谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.