我的数据库看起来像这样:
[foods]
foods_id, foods_name, groups_id, producers_id
[producers]
producers_id, producers_name
[groups]
groups_id, groups_name
PHP:
<?php
$producers = mysql_query('SELECT p.producers_name,p.producers_id FROM foods as f,producers as p WHERE p.producers_id = f.producers_id AND f.groups_id = 1 GROUP BY p.producers_name');
//list the producer...
while($row = mysql_fetch_array($producers, MYSQL_ASSOC)){
$foods = mysql_query('SELECT foods_id, foods_name FROM foods WHERE producers_id = '.$row['producers_id'].' ORDER BY foods_name ASC');
while($row2 = mysql_fetch_array($foods, MYSQL_ASSOC)){
//list the foods under this producer...
}
}
?>
目标:
PRODUCER A
FOOD A
FOOD B
FOOD C
PRODUCER B
FOOD D
FOOD E
PRODUCER C
FOOD F
...
解:
<?php
$res = mysql_query('SELECT f.foods_id, f.foods_name, p.producers_id, p.producers_name FROM foods f, producers p WHERE p.producers_id = f.producers_id AND f.groups_id = '.$_GET['g'].' ORDER BY p.producers_name ASC, f.foods_name ASC');
$xproducers = array();
while($row = mysql_fetch_array($res , MYSQL_ASSOC)){
if(!array_key_exists($row['producers_id'],$xproducers)){
$xproducers[$row['producers_id']] = array('id'=>$row['producers_id'],'name'=>$row['producers_name'],'foods'=>array());
}
array_push($xproducers[$row['producers_id']]['foods'],array('id'=>$row['foods_id'],'name'=>$row['foods_name']));
}
?>
这个解决方案对我来说足够快,也许它并不完美,但它的工作做得很好:)我非常感谢大家的帮助!
干杯
答案 0 :(得分:1)
我无法理解为什么你先选择,这会得到相同的数据。
$res = mysql_query('SELECT f.foods_id, f.foods_name, p.producers_id, p.producers_name FROM foods f, producers p WHERE p.producers_id = f.producers_id AND f.groups_id = 1');
while($row = mysql_fetch_array($res , MYSQL_ASSOC)){
$producers[$row['producers_id']][$row['foods_id']] = $row;
}
答案 1 :(得分:0)
我会做的
mysql_query('SELECT producers_name, producers_id
FROM producers
WHERE producers_id IN
(SELECT producers_id FROM foods WHERE groups_id = 1)');
这应该更快。
祝你好运!