structure php data in mySQL
I've got a data schema like this:
cp
id te su
1 7 2
2 7 1
3 6 8
cl
id cp st
1 2 5
2 2 6
3 1 6
us
id na
.. ..
5 Joe
6 Mike
7 Tina
.. ..
I want to run a php function foo($te)
with foo(7)
to output data like this from mySQL
[0]
su: 1
st_list:
[0]
id:6
na:Mike
[1]
su: 2
st_list:
[0]
id:5
na:Joe
[1]
i开发者_开发百科d:6
na:Mike
I want to know how best to do this. Right now I'm able to use JOINs, but the result looks like this
[0]
su: 1
st_id:6
st_na:Mike
[1]
su: 2
st_id:5
st_na:Joe
[3]
su: 2
id:6
na:Mike
The su:2
is repeated... obviously that isn't a problem in this example, the problem is that in the real thing that su
represents a lot more data, that i'll be getting through "this" (whatever answer I choose) method.
EDIT: I hope you understand what I'm asking... I know a lot of you guys are way more knowledgable in mySQL and development in general than me, so that's why i'm asking in such a plain (I HAVE THS----> WANT THIS) way, because I think if I asked any more specifically I would end up making assumptions about the way it should run). I want an effecient solution, because this data is being used to populate search results.
Thanks!!!!!!!!!!
You will need to loop over the results yourself and build the array in the format you want. MySQL can't give you the results in the nested format you want. Here's a rough draft (untested):
$su = 0;
$st_list = array();
$nested = array();
foreach ($results as $row) {
if ($su != 0 && $row['su'] != $su) {
$nested[] = compact('su', 'st_list');
}
if ($su != $row['su']) {
$su = $row['su'];
$st_list = array();
}
$st_list[] = array(
'id' => $row['st_id'],
'na' => $row['st_na'],
);
}
$nested[] = compact('su', 'st_list');
Edit: Usually it's best to simply fetch all the results you want using a single SQL query. That is almost always the most efficient way to do it. But if it really matters to you (and this is a performance critical part of your application), the only way to know for sure is benchmark both methods. A lot depends on your database layout, number of rows, SQL indexes, etcetera.
SELECT distinct us.id,na FROM cp
LEFT JOIN cl ON cp.su = cl.cp
LEFT JOIN us ON us.id = cl.st
where te = "7"
Does this provide the results you are looking for?
Alternately,
SELECT su,us.id,na FROM cp
LEFT JOIN cl ON cp.su = cl.cp
LEFT JOIN us ON us.id = cl.st
where te = "7"
ORDER BY su
Is closer to the formatting you asked for in your post.
In your model, you can have something like these too...
function get_te($te)
{
$qry = $this->db->get_where('cp', array('te' => $te));
$raw_te = $qry->result_array();
$te = array();
$i = 0;
while($i < count($raw_te))
{
$te[$i]['su'] = $raw_te[$i]['su'];
$qry = $this->db->select('*')
->from('cl')
->join('us', 'us.id = cl.id')
->where('cp', $raw_te[$i]['id'])
->get();
$te[$i]['st_list'] = $qry->result_array();
$i++;
}
return $te;
}
精彩评论