如何基于另一个查询结果集执行MySQLi查询


How to perform MySQLi query based off of another query result set?

我知道有一种方法可以使用JOIN组合这三个查询,但我就是无法理解它。

我要做的是首先检索MessageIDSubscriberID。根据这些结果,我收集消息的数据和订阅者的数据:

$queued = $db->select("SELECT MessageID, SubscriberID FROM mailing_queue WHERE Paused = 0 ORDER BY StartDate ASC LIMIT 500");
if (!empty($queued)) { // if $queued exists
    $i = 0;
    foreach ($queued as $key => $value) {           
        $msg = $db->selectRow("SELECT Subject, Body FROM mailing_messages WHERE ID = '$value[MessageID]' LIMIT 1"); // Returns single row
        if ($msg) { // If $msg exists
            $to = $db->selectRow("SELECT Email, FirstName, LastName, History FROM mailing_subscribers WHERE ID = '$value[SubscriberID]' LIMIT 1"); // Returns single row
            if ($to) { // If $to exists
                // Send email & do other stuff
            }
        }
    }
}

基本上,如果可能的话,我试图在一个查询中获得Subject, Body, Email, FirstName, LastNameHistory

我知道一定有更有效的方法来做这件事。

所以这个查询应该给你一些东西来检查你的代码的if($to)段。你应该有行中所有可用的东西。

$queued = $db->select(
"SELECT
 mailing_queue.MessageID,
 mailing_queue.SubscriberID,
 mailing_messages.Subject, 
 mailing_messages.Body,
 mailing_subscribers.Email, 
 mailing_subscribers.FirstName, 
 mailing_subscribers.LastName, 
 mailing_subscribers.History 
 FROM mailing_queue
 INNER JOIN mailing_messages ON mailing_messages.ID = mailing_queue.MessageID
 INNER JOIN mailing_subscribers ON mailing_subscribers.ID = mailing_queue.SubscriberID
 WHERE mailing_queue.Paused = 0 
 ORDER BY mailing_queue.StartDate 
 ASC LIMIT 500");
foreach($queued as $key=>$to){
    //whatever your send your email code is, demonstration:
    echo $to['Subject'];
    echo $to['SubscriberID'];
    echo $to['FirstName'];
}