[英]Get rows where one column is unique and another column is the lowest value relative to the unique column
我正在努力解決一個相對簡單的問題,但就是無法解決它。
我有一個方法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)
我現在想使用數組中的數據來獲取包含在與周數相關的日程表中的所有信息。
我的問題在這里
方法二
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 中是否有查詢方法,我可以在其中將數組插入查詢並循環遍歷數組 (),如果這有意義的話?
如何改進/修復上述查詢?
我想您需要這樣的查詢:
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";
這將在將符合條件的行傳遞給父查詢時保持錦標賽和周數之間的關系。 這樣,即使您有一個合格的 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.