[英]Combining select queries
I am working with a MySQL database. 我正在使用MySQL数据库。 I am suppose to combine three select queries, to "improve performance".
我想结合三个选择查询,以“提高性能”。 Each select below is dependent on the previous ID retrieved.
下面的每个选择均取决于先前检索到的ID。
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. 我需要根据用户名参数选择user.name和group.ID。 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. 请根据需要使用join。 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. 我在您的查询的片段中添加了注释,这些片段已转换为
JOIN
子句。
Read more about the syntax of the JOIN
subclause of the SELECT
statement . 阅读有关
SELECT
语句的JOIN
子句的语法的更多信息。
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 = ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.