获取其中一列唯一且另一列是相对于唯一列的最低值的行

Get rows where one column is unique and another column is the lowest value relative to the unique column

我正在努力解决一个相对简单的问题,但就是无法解决它。

我有一个方法 getNextRound(),其中 returns 一个数字数组。数字代表数据库中的周数 table.

然后我有第二种方法 getUpcomingGames() 我调用第一种方法然后我想使用第一种方法中的数字在我的查询中使用。

这是一个例子:方法 1

public function getNextRound(){

        $sql = "SELECT min(weekNum) from schedule WHERE schedule.gameDateTime > NOW() GROUP BY tournament ORDER BY gameDateTime ASC";
        $stmnt = $this->db->query($sql);
        if ($stmnt->num_rows() > 0) {
            print_r($stmnt->result());
            return $stmnt->result();
        }
        return false;
    }

上述方法/查询的结果

array (size=3)
  0 => 
    object(stdClass)[24]
      public 'min(weekNum)' => string '38' (length=2)
  1 => 
    object(stdClass)[25]
      public 'min(weekNum)' => string '14' (length=2)
  2 => 
    object(stdClass)[26]
      public 'min(weekNum)' => string '7' (length=1)

我现在想使用数组中的数据获取与周数相关的时间表 table 中包含的所有信息。

我的问题就在这里

方法二

public function getUpcomingGames()
    {
//HERE I WANT TO GET ALL INFO FROM SCHEDULE WHERE ROUND = $week
        $rounds[] = $this->getNextRound();
        foreach ($rounds as $round) {
            $sql = "SELECT *  from  schedule WHERE weekNum = '$round' ORDER BY gameDateTime ASC ";
            $data[] = $this->db->query($sql);
            var_dump($data);
        }

错误:除其他外,我收到一个数组到字符串的转换错误。

我查看了 codeigniter 文档,但找不到我要找的方法。

DB TABLE

问题:

我想您需要这样的查询:

SELECT *
FROM schedule AS parent
JOIN (
    SELECT tournament,
           MIN(weekNum) AS nextWeek
    FROM schedule AS child
    WHERE gameDateTime > NOW()
    GROUP BY tournament
) ON parent.tournament = child.tournament AND parent.weekNum = child.nextWeek
ORDER BY gameDateTime";

这将在将符合条件的行传递给父查询时保持锦标赛和 weekNums 之间的关系。这样,即使您的非资格锦标赛的周数符合条件,结果集仍然为真。

等效的 codeigniter 是:

$this->db->select('tournament, MIN(weekNum) AS nextWeek');
$this->db->from('schedule');
$this->db->where('gameDateTime >', 'NOW()', false);
$this->db->group_by('tournament');
$subquery = $this->db->get_compiled_select();


// $this->db->select('*'); <- not necessary
$this->db->from('schedule AS parent');
$this->db->join('(' . $subquery . ') AS child', 'parent.tournament = child.tournament AND parent.weekNum = child.nextWeek');
$this->db->order_by('gameDateTime');
return $this->db->get()->result();