简体   繁体   中英

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

I know there is a way to combine these three queries using JOIN , but I just can't wrap my head around it.

What I am doing is first retrieving a MessageID and SubscriberID . Based off of these results, I gather data for the message and data for the subscriber:

$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

            }
        }
    }
}

Basically, I am trying to get Subject , Body , Email , FirstName , LastName and History all in one query if possible.

I know there must be a much more efficient way of doing this.

So this query should give you something to foreach against in the if($to) segment of your code. You should have everything available to you in the row.

$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'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM