SQL / PHP:显示数据库中销量最高的3个产品

时间:2016-01-07 11:44:43

标签: php mysql sql mysqli count

我有一个包含以下表格的数据库:

 - 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 )

我想在我的主页上展示最畅销的3款产品,但无法做到这一点。

我试过了:

$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;";

我似乎无法找到在此查询中放置'count'的位置和方式。 感谢

4 个答案:

答案 0 :(得分:1)

试试这个:

$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";

答案 1 :(得分:0)

请尝试以下查询:

$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";

答案 2 :(得分:0)

试试这个:

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;";

答案 3 :(得分:0)

选择p.name作为'产品名称',x.total as' Total'
来自产品p
内连接(选择product_id为product_id,sum(number)为order_count group by product_id的总和)x
在x.product_id = p.product_id
按x.total DESC限制3;

排序