SQL/PHP: Show top 3 most sold products from database

扶醉桌前 提交于 2021-02-08 08:39:25

问题


I have a database containing the following tables:

 - product (product_id / name / price / image_id / description)
 - order ( order_id / date / status / email )
 - order_count ( order_id / product_id / number )
 - image (image_id / image_link )

I'd like to show the 3 most sold products on my homepage, but can't wrap my head around doing this.

I tried this:

$sql = "SELECT" * 
FROM 'product' INNER JOIN 'afbeelding' 
WHERE 'product'.'image_id' = 'afbeelding'.'image_id'
GROUP BY 'product_id'
ORDER BY 'product_id' DESC
LIMIT 3;";

I can't seem to find out where and how to place a 'count' in this query.. Thanks


回答1:


Try this:

$sql = "SELECT SUM(order_count.number) AS total, image.image_link AS image_link 
FROM product JOIN order_count 
ON product.product_id = order_count.product_id 
JOIN image ON product.image_id = image.image_id
GROUP BY order_count.product_id 
ORDER BY total DESC 
LIMIT 3";



回答2:


Please try below query :

$sql = "SELECT p.*,af.*, IFNULL(SUM(oc.number), 0) as total_quantity 
FROM (`product` as p) 
INNER JOIN `afbeelding` as af ON `af`.`image_id` = `p`.`image_id` 
INNER JOIN `order_count` as oc ON `oc`.`product_id` = `p`.`product_id` 
GROUP BY `p`.`product_id` ORDER BY `total_quantity` DESC LIMIT 3";



回答3:


try with this:

SELECT * FOM products p INNER JOIN order_count oc 
ON p.product_id=oc.product_id 
GROUP BY 'product_id'
ORDER BY 'product_id' DESC
LIMIT 3;";



回答4:


select p.name as 'Product Name', x.total as 'Total'
from product p
inner join (select product_id as product_id, sum(number) as total from order_count group by product_id) x
on x.product_id = p.product_id
order by x.total DESC limit 3;



来源:https://stackoverflow.com/questions/34654322/sql-php-show-top-3-most-sold-products-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!