Reputation: 6313
I have 2 tables CP and CS structured like this.
CP
id tu su
1 7 1
2 7 2
.---------------------------------.
CS
id st cp
1 8 1
2 9 1
3 9 2
4 2 1
.--------------------------------.
I want to make a function get_cp($tu) to return the data like this. get_cp(7) =
su
'1'
[0] = array('st'=>'8')
[1] = array('st'=>'9')
[2] = array('st'=>'2')
'2'
[0] = array('st'=>'2')
It seems like I could use GROUP_CONCAT to make a X deliminated string and then parse it...but I was wondering if there is a "better" way. Parsing strings seems like it is wasteful, it would be great if mySQL could just return the data like this. Should I just use no GROUP at all, and then use php to group things together after I have a big list of duplicates?
Thanks! And please ask questions if your unsure what I'm asking. Thanks!!
Upvotes: 0
Views: 383
Reputation: 73031
You can use GROUP_CONCAT()
. Generally speaking, I think if you can do it on the DB side, you should.
However, in this case, you are going to have to loop over the results to construct the array you described no matter what query you use.
As such, I'd do the following query and build the grouping with PHP.
$data = array();
$results = mysql_query('SELECT st, cp FROM CS');
while ($row = mysql_fetch_assoc($results)) {
$data[$row['cp']][] = $row['st'];
}
Note: This is not ordered for performance. If you need them in a certain order, then add an ORDER BY
.
Upvotes: 1