1

I am working with a MySQL database. I am suppose to combine three select queries, to "improve performance". Each select below is dependent on the previous ID retrieved.

So far, I've tried the following...

# multiple select from tables
select user.name, group.ID
  from user as u, group as g
  where u.name = <name_here>

# inner join...
select user.ID, group.ID,
  from user
    inner join group
      on user.ID = group.ID

I need to select the user.name and group.ID based on a username param. Is there a way to query this data in a single statement?

1
  • I just updated for clarity.
    – Kyle
    Aug 24, 2016 at 13:17

4 Answers 4

3

I don't know if I understand your need, lets try:

Try to use this query:

select pGroupMatch.GroupID, ProfileData.ID
from pUserMatch
inner join pGroupMatch on pGroupMatch.GroupID = pUserMatch.GroupID 
inner join ProfileData on ProfileData.id = pGroupMatch.ProfileID 
where pUserMatch.username = "<username>";

Check if you can create indexes for improve your query, if you can try it:

CREATE INDEX idx_pUserMatch_01 ON pUserMatch (GroupID);
CREATE INDEX idx_pGroupMatch_01 ON pGroupMatch (ProfileID);
1

Please use join for your requirement. Please try below query

select t3.* from Profiles.pUserMatch t1 
left join Profiles.pGroupMatch t2 ON t2.GroupID=t1.GroupID 
left join Profiles.ProfileData t3 ON t3.ID=t2.ProfileID 
where t1.username = "<username>";

I hope above query will help you.Please feel free to comment. Thanks.

1

This is the query you get by joining the tree queries you already have:

SELECT pd.*
FROM Profiles.ProfileData pd
  # ... where ID = "<profile_id>", profile_id = select ProfileID from ...
  INNER JOIN Profiles.pGroupMatch pm ON pd.ID = pm.ProfileID
  # ... where GroupID = "<group_id>", group_id = select GroupID from ...
  INNER JOIN Profiles.pUserMatch pu ON pm.GroupID = pm.GroupID
WHERE pm.username = "<username>" 

I put in comments the fragments of your queries that gets converted to JOIN subclauses.

Read more about the syntax of the JOIN subclause of the SELECT statement.

0

You don't need foreign keys to join stuff:

select p.* from Profiles.pUserMatch u
join Profile.pGroupMatch g on u.GroupID = g.GroupID
join Profile.ProfileData p on g.ProfileID = p.ID
where u.username = ?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.