开发者

Is there a way to combine these queries

开发者 https://www.devze.com 2023-03-29 08:31 出处:网络
Is is efficient to combine two queries into one? What are advantages or disadvant开发者_开发知识库ages?

Is is efficient to combine two queries into one? What are advantages or disadvant开发者_开发知识库ages? Can someone help me combine these two queries:

SELECT quiz_id from questions WHERE question = 10

SELECT quiz_number FROM quizzes WHERE quiz_id = 5

quiz_id has 1 to many relationship with question. So for one specific question there will be only one quiz_id, but one quiz_id can have up to 20 question under it.


Not really sure what you mean by combine, perhaps you mean subselect / subquery? In that case try:

---    IN syntax
SELECT quiz_number FROM quizzes WHERE quiz_id IN
       (SELECT quiz_id FROM questions WHERE question = 10);

---    = syntax. This will work only if the subquery returns one value 
SELECT quiz_number FROM quizzes WHERE quiz_id = 
       (SELECT quiz_id FROM questions WHERE question = 10);


Assuming the relationship from your 2 posted queries, and that the value 5 in the second query is the result from the first query:

SELECT quiz_number FROM quizzes qz
INNER JOIN questions qu on qu.quiz_id = qz.quiz_id
WHERE question = 10


you can use aliases

SELECT question.quiz_id, quiz.quiz_number from questions question,quizzes quiz WHERE question.question = 10 and quiz.quiz_id =5
0

精彩评论

暂无评论...
验证码 换一张
取 消