如何以更干净的方式执行这些MySQL子查询?

时间:2015-05-03 11:47:33

标签: php mysql mysqli

使用使用mysql代替mysqli/pdo的旧代码,所以不要担心这一点,我稍后会更新查询。

即使我当前的方法有效,但我很肯定有一种更简洁的方法,而不是查询和3个子查询。我主要想学习如何更好地增强我的查询并减少它们的数量 我想做的是

  1. echo显示每个日期的所有数据,日期显示在顶部
  2. 显示用户旁边某一天的每个用户的条目数
  3. 对于每个日期,在上述2位数据的底部,显示具有最多条目数的用户

    $query = mysql_query('SELECT * FROM entries GROUP BY DATE(dt)');
    
    $g = 0;
    
    while ($row = @mysql_fetch_array($query)) 
    {
    
        $group[$g] = date('y-m-d', strtotime($row['dt']));
        echo $group[$g] . "<br />";
    
        //display the person's name for today with their count
        $dayquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC');
            while ($today = @mysql_fetch_array($dayquery)) 
            {
                echo $today['first_name'] . " | " . $today['total'] . "<br />";
            }   
    
            //display the highest count for today
            $topquery = mysql_query('SELECT COUNT(username) as highest FROM entries WHERE DATE(dt) = "'.$group[$g].'" GROUP BY username ORDER BY COUNT(username) DESC LIMIT 1');
                while ($toptoday = @mysql_fetch_array($topquery)) 
                {
                    echo "Highest today: " . $toptoday['highest'] . "<br /><br />" ;
                } 
    
                //display the users with the highest count for today
                echo "Highest users: ";
                $userstopquery = mysql_query('SELECT *, COUNT(username) as total FROM entries WHERE DATE(dt) = "'.$group[$g].'" AND COUNT(username) = "' . $toptoday['highest'] . '" AND GROUP BY username');
                    while ($topusers = @mysql_fetch_array($userstopquery)) 
                    {
                         echo $topusers['first_name'] . "<br />" ;
                    } 
    
        $g++;
    
    }
    
  4. 我遇到的麻烦是,当我尝试减少这些子查询并使用MAX时,它只输出最高计数但不输出每个日期的所有数据,这就是我需要的,包括输出具有该特定日期的最多条目的用户。

0 个答案:

没有答案