0

I have a database with two tables groups and members. The columns from these tables are below.

Groups table: group_id,group_name

Members table: member_id,group_id,status

I have an app that needs to display a list of groups along with the groups members. What is the most efficient way to say SELECT * from groups then for each group/row returned do another select on the members table to query the members (for example SELECT * FROM members WHERE group_id=X).

3
  • 3
    Do you know how to use JOIN? If not, good place to start. Commented Aug 28, 2014 at 19:18
  • I suppose the join gets the data back but then I have a separate row for each member. In my application I want to show each group then the member of each group separately. Ideally in the app I'd pass through an array of groups then groups.member would be the members. I'm not sure who I would get this type of output from a join? Thanks for the fast response as well! Commented Aug 28, 2014 at 19:35
  • 1
    You'll have to decide what to do in your application code and what to do in your query. Sometimes MySQL is not the place you want to do certain data transformation operations. Commented Aug 28, 2014 at 19:37

3 Answers 3

2
select 
   g.group_id,
   g.group_name,
   m.member_id,
   m.status

from groups g 
     inner join members m on g.group_id = m.group_id
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming that both members and groups have a column named group_id, you can use join to fetch the results you want:

select m.*
from members as m
     inner join groups as g on m.group_id = g.group_id
where group_id = X

Comments

0
SELECT * 
FROM groups g
LEFT JOIN members m
ON g.group_id = m.group_id

This would return all groups and their members.

You can introduce variables, so for example

SET @groups = (SELECT TOP 1 group_id FROM groups)

and add it to your query.

SELECT * 
FROM groups g
LEFT JOIN members m
ON g.group_id = m.group_id
WHERE g.group_id = @groups

1 Comment

top? Isn't that for SQL Server? I think you mean select group_id from groups limit 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.