用户表:
Order_items表:
订单表:
$sql[2] = "SELECT p.p_name, o.created, COUNT(oi.id) AS db FROM products AS p
INNER JOIN order_items AS oi ON oi.product_id = p.id
INNER JOIN orders AS o ON o.id = oi.order_id
GROUP BY p.p_name
ORDER BY db DESC, o.created DESC
LIMIT 1";
$result3= mysqli_query($conn,$sql[2]) or die(mysqli_error());
if (mysqli_num_rows($result3)>0)
{
while ($record = mysqli_fetch_array($result3))
{
echo $record['p_name']." - ".$record['db']." - ".$record['created']."<br/>";
}
}
我想要计算最有序的产品名称,以及如何销售曼尼产品,以及订购此产品的最后日期。在这种情况下,结果如下: Barack - 4 - 2016-12-15 09:36:21但我的SELECT只计算3.任何想法我该如何解决?
答案 0 :(得分:0)
试试这个:
SELECT
p.p_name,
MAX(o.created) AS created,
COUNT(oi.id) AS db
FROM order_items AS oi
LEFT JOIN orders AS o ON oi.order_id= o.id
INNER JOIN products AS p ON p.id = oi.product_id
GROUP BY oi.product_id
ORDER BY COUNT(oi.id) DESC
LIMIT 1
<强> 更新 强>
因为表order_id = 3
中没有Orders
,所以INNER JOIN
会给你3,如果你想获得4,请使用LEFT JOIN
。