SELECT

时间:2018-03-21 12:46:00

标签: mysql sql

我想为表格选择我的数据库,并希望在SELECT时计算折扣价格和价格(现在的价格)。

这是我的查询

$sql = "SELECT *, SUM((pricebefore - price ) / price * 100) AS discount FROM products  WHERE price IS NOT NULL ORDER BY ID desc LIMIT $no_of_records_per_page OFFSET $offset";

所以我想得到所有数据,然后将价格与价格相比,价格比/价格和* 100,以便我得到百分比折扣,并希望将其保证为AS折扣。

但我总是得到这个错误:

Query failed: ERROR:  operator does not exist: character varying - character varying
LINE 1: SELECT *, SUM((pricebefore - price ) / price * 100) AS disco...
                                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

但是为什么......我没有找到问题,尝试了许多事情,比如没有SUM或者什么都没有效果

1 个答案:

答案 0 :(得分:0)

如果price_before位于同一行,则不需要sum()

SELECT p.*, (p.pricebefore - p.price ) / p.price * 100 AS discount
FROM products
WHERE price IS NOT NULL
ORDER BY ID DESC
LIMIT $no_of_records_per_page OFFSET $offset;

pricebeforeprice似乎是字符串,而不是数字。 MySQL通常会转换它们,但您可以进行显式转换:

SELECT p.*, ( cast(p.pricebefore as numeric(20, 4)) - cast(p.price as numeric(20, 4)) / cast(p.price as numeric(20, 40)) * 100 AS discount
FROM products
WHERE price IS NOT NULL
ORDER BY ID DESC
LIMIT $no_of_records_per_page OFFSET $offset;