简体   繁体   English

做一个查询:最好的方法是什么?

[英]Do it on one query: What's the best way?

I'm building a PHP5 application and I need to list the projects in it and all related information about them.我正在构建一个 PHP5 应用程序,我需要列出其中的项目以及有关它们的所有相关信息。 For that, I have three tables, named: kc_projects , kc_project_members and kc_users .为此,我有三个表,分别命名为: kc_projectskc_project_memberskc_users I have ID in all of them, and have a column in each row in kc_project_members linking the respective user to the project he is registered in.我在所有这些中都有 ID,并且在kc_project_members的每一行中都有一列将相应的用户链接到他注册的项目。

For now, I have this query:现在,我有这个查询:

SELECT * FROM kc_projects AS p
INNER JOIN kc_project_members AS pm
ON pm.PROJECT_ID = p.ID
INNER JOIN kc_users AS u
ON u.ID = pm.USER_ID

But it isn't working as I would like, because it actually retrieves the results I want, but not in the way I want.但它没有按我的意愿工作,因为它实际上检索了我想要的结果,但不是以我想要的方式。 It creates an array, and another array, and inside that array I have another array containing the query results.它创建一个数组和另一个数组,在该数组内我有另一个包含查询结果的数组。 It also creates me a duplicated result for each user, which means that if I have just one user registered in that project, it just returns me one project.它还会为每个用户创建一个重复的结果,这意味着如果我在该项目中只有一个用户注册,它只会返回一个项目。 But if I have more, it return's me arrays as much as the registered users, and that arrays have always the same project information.但是如果我有更多,它会返回我 arrays 和注册用户一样多,并且 arrays 始终具有相同的项目信息。 I would like him to just return one project, and inside it an array containing the users.我希望他只返回一个项目,并在其中包含一个包含用户的数组。

Is there anyway to do this, the right way?无论如何,正确的方法是这样做的吗?

Thanks,谢谢,
Scorch烧焦

I'm assuming that by arrays you mean result sets...我假设 arrays 你的意思是结果集......

Yes - it is possible, but probably not exactly as you've imagined it, because all result sets must have the same count of columns, which would not be possible in case you have say... 2 project members for project with id 1 and 5 project members for project with id 7.是的-这是可能的,但可能与您想象的不完全一样,因为所有结果集必须具有相同的列数,如果您说... 2 个项目成员,ID 为 1 的项目,这是不可能的以及 5 个项目成员,用于 id 为 7 的项目。

You'll have to specify exactly which columns you want to be returned - SELECT * won't do the trick(and it's a bad thing to do anyway, especially if good performance is required).您必须准确指定要返回的列 - SELECT *不会解决问题(无论如何这是一件坏事,尤其是在需要良好性能的情况下)。 And also, the users' ids, usernames or whatever columns you need to get for the referenced users per project will have to be concatenated in a string, which you should parse later with PHP.此外,用户的 id、用户名或您需要为每个项目的引用用户获取的任何列都必须连接在一个字符串中,稍后您应该使用 PHP 对其进行解析。

Here's an example:这是一个例子:

SELECT p.ID, p.PROJECT_NAME, GROUP_CONCAT(u.USERNAME SEPARATOR ',') AS PROJECT_MEMBERS
FROM kc_projects p
     JOIN kc_project_members pm ON p.ID=pm.PROJECT_ID
     JOIN kc_users u ON pm.USER_ID=u.ID
GROUP BY p.ID;

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

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