如何根据另一个查询结果集执行MySQLi查询?

时间:2015-10-18 15:39:24

标签: php

我知道有一种方法可以使用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

            }
        }
    }
}

基本上,我想在一个查询中获取SubjectBodyEmailFirstNameLastNameHistory可能。

我知道必须有一种更有效的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

因此,此查询应该会在代码的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'];
}