繁体   English   中英

组合选择查询

[英]Combining select queries

我正在使用MySQL数据库。 我想结合三个选择查询,以“提高性能”。 下面的每个选择均取决于先前检索到的ID。

到目前为止,我已经尝试了以下方法...

# 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

我需要根据用户名参数选择user.name和group.ID。 有没有一种方法可以在单个语句中查询此数据?

我不知道我是否了解您的需求,请尝试:

尝试使用此查询:

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

检查是否可以创建索引来改善查询,如果可以尝试的话:

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

请根据需要使用join。 请尝试以下查询

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

希望以上查询对您有所帮助。请随时发表评论。 谢谢。

这是通过加入已有的树查询而获得的查询:

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>" 

我在您的查询的片段中添加了注释,这些片段已转换为JOIN子句。

阅读有关SELECT语句JOIN子句的语法的更多信息。

您不需要外键来加入内容:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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