简体   繁体   中英

Combining select queries

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?

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);

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.

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 .

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 = ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM