Search code examples
sqlderby

Apache Derby SQL - select number of related rows between two tables


im using Apache Derby open source Database, i have two tables :

QUESTIONS:
Q_id - auto increment integer
Qtext - varchar(300)

ANSWERS:
A_id - auto increment integer
Atext - varchar(300)
Q_id - FOREIGN KEY integer not null

for each question there's more than one answer, and it can be that a question has no answers so what i want to do is to write a (Apache derby sql) statement which does the follows :

For each question in QUESTIONS table i want to count how many answers it has in ANSWERS TABLE, most important is for question that has no answers i want the result result to be 0.

Example :

SEE EXAMPLE IN THIS PICTURE

Thanks.


Solution

  • select Questions.QText
    , count(Answers.AText)
    from Questions
    left outer join Answers on Answers.Q_Id = Questions.Q_Id
    group by Questions.QText
    

    Update:

    You can use MAX on the question text that way you won't have to group by q_text

    select Questions.Q_id
    , max(Questions.qtext)
    , COUNT(Answers.q_id)
    from Questions
    left join Answers on Answers.Q_id = Questions.Q_id
    group by Questions.Q_id