简体   繁体   中英

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. For that, I have three tables, named: kc_projects , kc_project_members and kc_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.

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

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.

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

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;

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