0

我不知道如何合并这两个查询并立即为它们获取结果。

        $q1 = "SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score 
            FROM questions_and_exercises q, `lesson-question` lq 
            LEFT JOIN answers a ON (a.uid=? AND a.qid=lq.qid)
            LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id)
            WHERE q.id=lq.qid AND lq.lid=?";
        $q2 ="SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score
             FROM questions_and_exercises q,
             `questions from-to` qft
            LEFT JOIN answers a ON (a.uid=? AND a.qid=qft.qid)
            LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id)
            WHERE q.id=qft.qid AND qft.to_uid=?";

建议?提前致谢

4

2 回答 2

1

使用UNION来解决这个问题。

但是在这种情况下,我认为UNION甚至不需要:

$q1 = "SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score 
        FROM questions_and_exercises q, `lesson-question` lq 
        LEFT JOIN answers a
        ON a.qid=lq.qid
        LEFT JOIN `answer_chk_results` acr 
        ON acr.aid=a.id
        WHERE q.id=lq.qid AND a.uid = ? (lq.lid = ? OR qtf.to_uid = a.uid)";

它会将这两个结果组合成更多行。

$q1 = "SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score 
        FROM questions_and_exercises q, `lesson-question` lq 
        LEFT JOIN answers a ON (a.uid=? AND a.qid=lq.qid)
        LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id)
        WHERE q.id=lq.qid AND lq.lid=?
        UNION # ALL
        SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score
         FROM questions_and_exercises q,
         `questions from-to` qft
        LEFT JOIN answers a ON (a.uid=? AND a.qid=qft.qid)
        LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id)
        WHERE q.id=qft.qid AND qft.to_uid=?";

使用UNIONUNION ALL取决于是否要合并相同的行。AnUNION要求两个SELECTs 具有相同数量的列,并将使用第一个SELECTs 别名。

可以像这样简化最后一个查询:

        SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score
        FROM questions_and_exercises q,
        `questions from-to` qft
        LEFT JOIN answers a 
        ON a.qid=qft.qid
        LEFT JOIN `answer_chk_results` acr 
        ON acr.aid=a.id
        WHERE q.id=qft.qid AND qft.to_uid=? AND qtf.to_uid = a.uid

基本上,既然是相同的值,与 比较to_uid?再与 比较就足够to_uiduid。这与通过 比较它们的结果相同ON

于 2012-07-30T06:50:35.520 回答
0

全部使用联合

$q1 = "SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score  
            FROM questions_and_exercises q, `lesson-question` lq  
            LEFT JOIN answers a ON (a.uid=? AND a.qid=lq.qid) 
            LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id) 
            WHERE q.id=lq.qid AND lq.lid=? union all
            SELECT q.id, q.content, a.id, a.content, a.addDT, acr.score 
             FROM questions_and_exercises q, 
             `questions from-to` qft 
            LEFT JOIN answers a ON (a.uid=? AND a.qid=qft.qid) 
            LEFT JOIN `answer_chk_results` acr ON (acr.aid=a.id) 
            WHERE q.id=qft.qid AND qft.to_uid=?"; 
于 2012-07-30T06:51:28.627 回答