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

时间:2020-03-09 04:44:32

标签: php mysql sql codeigniter codeigniter-3

我正在为一个相对简单的问题而苦苦挣扎,但无法解决这个问题。

我有一个方法getNextRound()返回一个数字数组。数字代表db表中的星期数。

然后有第二个方法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)

我现在想使用数组中的数据来获取计划表中包含的与周数有关的所有信息。

我的问题在这里

方法2

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文档,但是找不到我想要的方法。

数据库表 qu

问题:

  • CI中是否有查询方法,如果可以的话,我可以在其中将数组插入查询并遍历array()?

  • 如何改善/修复以上查询?

1 个答案:

答案 0 :(得分:1)

我想您需要这样的查询:

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之间的关系。这样,即使您有不符合资格的WeekNum锦标赛,结果集也将保持正确。

等效于代码点火器的是:

$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();