Fox
Fox

Reputation: 459

How to join two queries in SQL from 3 tables?

I have 3 tables (M:N) - Tests, Tests_Questions, Questions.

Tests

ID
Name

Test_Questions

IDTests
IDQuestions

Questions

ID
Text

What I need is select all from tests and count of question related to this test.

Can you please help me with this query? I am not able to solve it.

Upvotes: 0

Views: 31

Answers (1)

dotnetom
dotnetom

Reputation: 24916

Use join and grouping:

SELECT t.ID, t.Name, COUNT(tq.IDQuestions) as numberOfQuestions
FROM Tests t INNER JOIN Test_Questions tq ON t.ID = tq.IDTests
GROUP BY t.ID, t.Name

Since you only need counts it is enough to join just Tests and Test_Questions tables, you don't need Questions

Upvotes: 1

Related Questions