【问题标题】:Get rows where one column is unique and another column is the lowest value relative to the unique column获取其中一列是唯一的并且另一列是相对于唯一列的最小值的行
【发布时间】:2020-03-09 04:44:32
【问题描述】:

我正在为一个相对简单的问题而苦苦挣扎,但就是想不通。

我有一个方法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 文档,但找不到我要查找的方法。

数据库表

问题:

  • CI 中是否有一种查询方法,我可以在其中将数组插入到查询中并循环遍历数组 (),如果这有意义的话?

  • 如何改进/修复上述查询?

【问题讨论】:

  • 在第二个中使用 IN QUERY
  • 我应该保留foreach() 循环吗?
  • 那么不需要使用foreach()。但是在使用IN 之后比较结果是否与您现在得到的结果相同?
  • @TimothyCoetzee 您实际上需要这两种方法还是很高兴将它们合并为一种优雅的方法?
  • tournament 列不包含在您的屏幕截图中。您没有提供完整的架构。您的第二次查询尝试“取消关联”tournamentweekNum - 这意味着下面的所有答案都注定不准确,您需要完全重新考虑您的方法。在此之前,您将使用过去锦标赛的 weekNums 生成结果集。

标签: php mysql sql codeigniter codeigniter-3


【解决方案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,结果集仍然是正确的。

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

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多