I have MySQL query that selects user names and theirs knowledge (may be more than one).
It returns something like this…
array(5) {
[0]=>
array(5) {
["user_id"]=>
string(2) "30"
["name"]=>
string(6) "foo1"
["knowledge"]=>
string(15) "Basic Materials"
}
[1]=>
array(5) {
["user_id"]=>
string(2) "33"
["name"]=>
string(6) "foo2"
["knowledge"]=>
string(15) "Basic Materials"
}
[2]=>
array(5) {
["user_id"]=>
string(2) "34"
["name"]=>
string(10) "foo3"
["knowledge"]=>
string(9) "Eating"
}
[3]=>
array(5) {
["user_id"]=>
string(2) "34"
["name"]=>
string(10) "foo3"
["knowledge"]=>
string(9) "Financial"
}
[4]=>
array(5) {
["user_id"]=>
string(2) "34"
["name"]=>
string(10) "foo3"
["knowledge"]=>
string(8) "Services"
}
}
As you can see, in this example, it does returns five entries. However, three of them have duplicate IDs (and names). I’m looking for a way to return only three entries like this…
Is it possible to do in the query?
array(5) {
[0]=>
array(5) {
["user_id"]=>
string(2) "30"
["name"]=>
string(6) "foo1"
["knowledges"]=>
array(1) {
[0] => string(15) "Basic Materials"
}
}
[1]=>
array(5) {
["user_id"]=>
string(2) "33"
["name"]=>
string(6) "foo2"
["knowledges"]=>
array(1) {
[0] => string(15) "Basic Materials"
}
}
[2]=>
array(5) {
["user_id"]=>
string(2) "34"
["name"]=>
string(10) "foo3"
["knowledges"]=>
array(1) {
[0] => string(15) "Eating"
[1] => string(15) "Financial"
[2] => string(15) "Services"
}
}
}
Other option I see is to process results on server-side.
Here is how the query looks like:
SELECT `profiles`.`user_id`, `users`.`name`, `users`.`surname`, `users`.`country`, `profile_knowledges`.`knowledge`
FROM `profiles`
JOIN `users`
ON (`users`.`id` = `profiles`.`user_id`)
JOIN `profile_knowledges`
ON (`profile_knowledges`.`profile_id` = `profiles`.`id`)
For this particular case you could write something like this:
However it’s a better idea to use an ORM such as Doctrine to handle such situations.