PHP Mysql复杂的Order By

时间:2016-08-24 18:10:19

标签: php mysql

在我的SQL查询中

SELECT unit_price,price_counter FROM products

它在表格中显示结果。该表的最后一列命名为"价格和计数器的百分比"。 PHP中该列的公式如下:

$PercentCompare = round((float)(($UnitPrice-$PriceCounter)/$UnitPrice) * 100);

现在客户端要求根据最后一列对表进行排序。如果该列也是我products表中的字段或列,我可以轻松地执行ORDER BY,但该列仅在使用上述公式后显示在网页表上。

问题是,如果该列是计算/公式的结果,我如何排序或使用ORDER BY?我正在使用准备好的声明。我这样做:

SELECT unit_price,price_counter FROM products ORDER BY round((float)((unit_price-price_counter)/unit_price) * 100)

编辑第二次尝试:

$InsertCalculation = ", round((float)((unit_price - price_counter)/unit_price) * 100) AS percentagecounter";
$QueryOrderBy = "perc_list_count";
$MyQuery = "SELECT itemid, address, city, state, zipcode, county, nameofowner, unit_price, price_counter, status" . $InsertCalculation . " FROM products WHERE itemid LIKE ? AND address LIKE ? AND city LIKE ? AND state LIKE ? AND zipcode LIKE ? AND county LIKE ? ORDER BY " . $QueryOrderBy . " ASC";

1 个答案:

答案 0 :(得分:0)

您可以计算然后按顺序排序。像这样的东西

SELECT unit_price,price_counter,
  ROUND(((unit_price-price_counter)/unit_price) * 100) as percentage_price
FROM products
ORDER BY percentage_price ASC

您可以在此处计算percentage_price,然后按

进行排序