我无法弄清楚如何合并这两个查询并立即获得结果。
$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=?";
Suggetions?提前致谢
答案 0 :(得分: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=?";
使用UNION
或UNION ALL
,具体取决于您是否要合并相同的行。 UNION
要求两个SELECT
具有相同数量的列,并且将使用第一个SELECT
个别名。
你可以放宽上次查询,如下所示:
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_uid
与uid
进行比较。与通过ON
比较它们的结果相同。
答案 1 :(得分: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=?";