如何使用mysql查询只查询价格和促销价格之间价格比最大的产品

时间:2015-10-31 07:26:20

标签: php mysql

我有这个问题:

SELECT id,bg_product_name,product_price,promo_price FROM products 
WHERE active="1" order by ((product_price / promo_price) > 0) ASC limit 5

样本记录:

#id #bg_product_name  #product_price  #promo_price
74  Jewellery         30.00            28.00
75  Jewellery1        20.00            0.00
76  Jewellery2        30.00            25.00

等等。 我的查询返回记录,但它们没有按最大的价格差异排序。

完整查询:

SELECT 
p.id, bg_product_name, unique_name, product_price, promo_price,
 promo_end_date, available_qty, model, p.added_date, url, bg_category, free_delivery, 
free_option,supplier_name,link_name, (product_price / promo_price) as  p_ratio 
FROM 
products p, products_to_categories ptc, products_to_adverts pta, products_categories pc, adverts a 
WHERE 
p.id=ptc.product_id and ptc.category_id="156" and ptc.category_id=pc.id
 and p.active="1" having p_ratio > 0 and p.instock="1" and p.id=pta.product_id and
 available_qty > 0 AND pta.advert_id=a.id AND 
pta.advert_id not in (0) 
GROUP BY ptc.product_id order by p_ratio DESC,p.updated_date DESC LIMIT 5

5 个答案:

答案 0 :(得分:2)

你可以试试这个:

SELECT id,bg_product_name,product_price,promo_price 
FROM products 
WHERE active="1" 
ORDER BY ABS(product_price - promo_price) ASC
LIMIT 5

答案 1 :(得分:2)

您可以使用WHERE子句而不是接受的答案中的HAVING子句,在大多数情况下,这种子句在性能方面更好...在一个条件下:没有负(促销)价格(合理的假设,我觉得呢?)
在这种情况下,您只需要处理一个值:promo_price == 0,如Jewellery1示例中所示。 "比率"对于该记录将是20.0 / 0.0 - >空值。 promo_price的任何其他值都将导致该比率为正数 因此,在完成其他操作之前,只需使用promo_price = 0.0过滤掉记录。

SELECT
    id,bg_product_name,product_price,promo_price, (product_price/promo_price) as ratio
FROM
    products 
WHERE
    active="1"
    AND promo_price > 0
ORDER BY
    ratio ASC
LIMIT
    5

或者甚至可能更好:同时保留列表中包含promo_price = 0的记录,但为比率指定一个不同的值,例如

SELECT
    id,bg_product_name,product_price,promo_price,
    if(promo_price>0, product_price/promo_price, 'free as in beer') as ratio
FROM
    products 
WHERE
    active="1"
ORDER BY
    ratio ASC
LIMIT
    5

答案 2 :(得分:1)

试试此代码

SELECT id, bg_product_name, product_price, promo_price, (product_price / promo_price) as p_ratio  FROM products 
WHERE active="1" GROUP BY products.id having p_ratio > 0 order by p_ratio ASC limit 5

订单必须是DESC

答案 3 :(得分:0)

试试这个:将(product_price / promo_price)添加到select子句然后按顺序执行。如果您不需要ratio > 0,请在where子句中添加0

SELECT id,bg_product_name,product_price,promo_price,(product_price / promo_price) as ratio FROM products 
WHERE active="1" and ratio > 0 order by ratio ASC limit 5

答案 4 :(得分:0)

试试这个

SELECT id,bg_product_name,product_price,promo_price,(product_price / promo_price) AS newDiff FROM products 
WHERE active="1" order by newDiff) ASC limit 5