-2

我希望你能帮我解决这个问题。我想运行一个query搜索表及其所有行且日期与当前月份匹配的程序。然后返回user_id. 我想要实现的是在 this 下收集前 5 个用户 ID query

如何更改此设置以找到当月的前 5 名?我通常能够弄清楚我的问题,但这个问题让我很难过。

这就是我目前所拥有的一切。

$top = mysqli_query($mysqli, "SELECT sum(amount) AS total FROM sales WHERE status = 'S' AND MONTH(date) = 1");

    while($row = mysqli_fetch_row($top))
         {

           $userid = $row['0'];

         }

更新:

$top = mysqli_query($mysqli, "SELECT user_id
    FROM
    (
        SELECT user_id, SUM(amount) total 
        FROM sales 
        WHERE status = 'S' 
        AND MONTH(date) = MONTH(CURDATE())
        AND YEAR(date)  =  YEAR(CURDATE())
        GROUP BY user_id
    ) q
        ORDER BY total DESC
        LIMIT 5");

           while($row = mysqli_fetch_row($top))
                {
                   $topsales[] = $row['0'];
                }

    foreach($topsales as $topsale) {
            echo $topsale;
    }
4

1 回答 1

2

您是否正在寻找这样的查询?

SELECT user_id
  FROM
(
  SELECT user_id, SUM(amount) total 
    FROM sales 
   WHERE status = 'S' 
     AND MONTH(date) = MONTH(CURDATE())
     AND YEAR(date)  =  YEAR(CURDATE())
  GROUP BY user_id
) q
 ORDER BY total DESC
 LIMIT 5

要不就

SELECT user_id 
  FROM sales 
 WHERE status = 'S' 
   AND MONTH(date) = MONTH(CURDATE())
   AND YEAR(date)  =  YEAR(CURDATE())
 GROUP BY user_id
 ORDER BY SUM(amount) DESC
 LIMIT 5

这是SLQFiddle演示

注意:使用MONTH()andYEAR()函数将阻止 MySql 使用您在date列上可能拥有的任何索引


现在你的 php 代码可能看起来像这样

$db  = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
    die('Cannot connect'); // TODO: better error handling
}
$sql = "SELECT user_id 
          FROM sales 
         WHERE status = 'S' 
           AND MONTH(date) = MONTH(CURDATE())
           AND YEAR(date)  =  YEAR(CURDATE())
         GROUP BY user_id
         ORDER BY SUM(amount) DESC
         LIMIT 5";

$topsales = array();

if ($query = $db->prepare($sql)) {
    $query->execute();
    $query->bind_result($user_id);

    while ($query->fetch()) {
        $topsales[] = $user_id;
    }
    $query->close();
} else {
    die('Unable to prepare: ' . $db->error); // TODO: better error handling
}
$db->close();

foreach ($topsales as $topsale) {
    echo $topsale . '<br>';
}
于 2013-07-04T04:39:23.903 回答