1

I have a database with multiple tables all tied by an ID. The tables would look something like:

TableA:
    user_id
    user_firstname
    user_lastname

TableB:
    user_id
    exam_result
    date_taken

Table A will only ever contain a single row (unique User_ID) but Table B can contain multiple rows per User_ID. Something like this:

TableA:
    user_id = 1
    user_firstname = blah
    user_lastname = blah

    user_id = 2
    user_firstname = blah
    user_lastname = blah

TableB:
    user_id = 1
    exam_result = F
    date_taken = somedate

    user_id = 1
    exam_result = E
    date_taken = somedate

    user_id = 1
    exam_result = U
    date_taken = somedate

    user_id = 2
    exam_result = A
    date_taken = somedate

    user_id = 2
    exam_result = A
    date_taken = somedate

My question is how can I get the data out of both tables but only ever return 1 row per unique ID... I think its called a Nested Select.

If I could get the results to display something like:

user_id1, user_first_name1, user_lastname1, (F, somedate, E, somedate, U, somedate)
user_id2, user_first_name2, user_lastname2, (A, somedate, A, somedate)

Hopefully it makes sense.

Thanks in advance.

1
  • From the top of my head, this is not possible. Explain us what are you trying to archieve so we can suggest you better ways of doing it. Commented Feb 26, 2013 at 19:46

1 Answer 1

3

I think you're looking for GROUP_CONCAT:

SELECT A.User_Id, A.user_firstname, A.user_lastname,
  GROUP_CONCAT(CONCAT(B.Exam_Result,',',B.Date_Taken))
FROM TableA A
  LEFT JOIN TableB B ON A.User_Id = B.User_Id
GROUP BY A.User_Id

SQL Fiddle Demo

If you want parentheses around the result, use another CONCAT:

CONCAT('(',GROUP_CONCAT(CONCAT(B.Exam_Result,',',B.Date_Taken)),')')

EDIT:

I've updated the answer to use a LEFT JOIN instead of an INNER JOIN to handle NULL values from TableB.

Sign up to request clarification or add additional context in comments.

8 Comments

He wants data from 2 columns for each row to be in the list.
@rcdmk: This answer should give that result.
@sgeddes thanks for that... it looks good. I will play with it and see what happens with my real data.
@sgeddes that works but only for data which has an ID in both tables... some of my data has an ID in table A but there are no rows in for that ID in table B. Anyway it can display a null for those ID's?
It actually combines all data together into one row: sqlfiddle.com/#!2/9cba4/1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.