MySQL中的相关子查询帮助

时间:2011-12-20 05:38:35

标签: php mysql sql correlated-subquery

我需要在表格中找到每个ID的最后一行,其中显示“是”,然后在同一个表中搜索该ID的下一个实例,以确保该条目为“否”。目前,这在查询结合使用php foreach时效果很好,该foreach使用第二个where子句中第一个查询的结果。数据集只有3000多行,整个过程非常低效,仅需4分钟即可完成。

我知道只有当我只有一个Where标准时我才能使用sql这样做,但是因为我有两个,所以我似乎已经碰壁了,并且感谢我能得到任何帮助。

提前致谢。

//Get max dispatchID where Available = 'Yes'
    <?php $sql = "SELECT a.memberID, MAX(a.dispatchID) as lastDispatchIDYes
                FROM  members_availability a
                WHERE available = 'Yes'
                GROUP BY memberID";
    $qry = $this->db->query($sql);              
    foreach($qry->result() as $row){
        $sql2 = "SELECT dispatchID, memberID, 
                     FROM members_dispatch WHERE memberID = '".$row->memberID."' AND dispatchID > '".$row->lastDispatchIDYes."' AND available = 'No'ORDER BY dispatchID ASC LIMIT 1";   
        $qry2 = $this->db->query($sql2);
        if($qry2->num_rows() > 0){                  
            echo $row->memberID." switched availability at ".$row->dispatchID."<br />";
        }           
    } ?>

2 个答案:

答案 0 :(得分:0)

这是一个解决问题的想法。

select tableNo.*
from
    (SELECT a.memberID, MAX(a.dispatchID) as lastDispatchIDYes
    FROM  members_availability a
    WHERE available = 'Yes'
    GROUP BY memberID) tableYes
    (SELECT a.memberID, a.dispatchID as dispatchIDNo
    FROM  members_availability a
    WHERE available = 'No'
    ) tableNo 
where tableYes.lastDispatchIDYes < tableNo.lastDispatchIDNo AND
      tableYes.memberID = tableNo.memberID

这将获取所有可用= NO的行,并且其dispatchID大于其可用的最后一行是。

答案 1 :(得分:0)

如果我了解您的需求,我认为此查询可能有所帮助:

SELECT `a1`.`memberID`, `a1`.`lastDispatchIDYes`, `b`.`dispatchID`, `b`.`available`
FROM (SELECT `a`.`memberID`, MAX(`a`.`dispatchID`) AS `lastDispatchIDYes`
FROM `members_availability` `a` WHERE `a`.`available` = 'Yes'
GROUP BY `a`.`memberID`) `a1`
INNER JOIN `members_availability` `b` ON `b`.`memberID` = `a1`.`memberID` AND `b`.`dispatchID` = `a1`.`lastDispatchIDYes` + 1;
$qry = $this->db->query($sql);              
foreach($qry->result() as $row) {
    echo $row->memberID . " switched availability at " . $row->lastDispatchIDYes . "<br />";
}

此外,似乎问题中提到的代码示例中的“echo”语句可能存在问题。 $row->dispatchID不是结果集中的有效值。我认为它应该是$row->lastDispatchIDYes。否?

编辑1:更新了查询,以便任何条目的“否”条目可以由dispatchID大于最后一个带“是”的条目的dispatchID。上面的原始查询只读取那些dispatchID紧接着的“No”条目。

SELECT DISTINCT `a1`.`memberID`, `a1`.`lastDispatchIDYes`
FROM (
    SELECT `a`.`memberID`, MAX(`a`.`dispatchID`) AS `lastDispatchIDYes`
    FROM `members_availability` `a`
    WHERE `a`.`available` = 'Yes'
    GROUP BY `a`.`memberID`
    ) `a1`
INNER JOIN `members_availability` `b`
    ON `b`.`memberID` = `a1`.`memberID`
    AND `b`.`available` = 'No'
WHERE `b`.`dispatchID` > `a1`.`lastDispatchIDYes`;

希望这有帮助!