基本问题!
我有两张桌子
生产
+-----+--------------+
| id | fruit_name |
+--------------------+
| 1 | Apple |
| 2 | Banana |
| 3 | Carrot |
+-----+--------------+
品种
+-----+---------------+----------------+
| id | fk_fruit_id | variety_name |
+-----+---------------+----------------+
| 1 | 1 | Cox |
| 2 | 1 | Braeburn |
| 3 | 2 | Chester |
| 4 | 3 | Kotaka |
| 5 | 3 | Imperial |
| 6 | 3 | Oneal |
+-----+---------------+----------------+
我想输出每种水果的品种清单。
APPLE - Cox, Braeburn
BANANA - Chester
CARROT - Kotaka, Imperial, Oneal
我现在的密码是
$query = "SELECT * FROM produce, varieties WHERE produce.id = varieties.fk_fruit_id";
$result = mysql_query($query) or die('Error : ' . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$produce_fruit_code = $row['fruit_code'];
$variety_name = $row['variety_name'];
echo $produce_fruit_code.' - '.$variety_name.'<br/>';
}
哪些输出:
Apple - Cox
Apple - Braeburn
Banana - Chester
Carrot - Kotaka
Carrot - Imperial
Carrot - Oneal
不在一百万英里之外,但仍然不在那里。非常感谢您的帮助,谢谢!
最佳答案
这不会让你一路走来,但它会让你得到你想要的大部分。有些边缘案例是有问题的。
$query = "SELECT * FROM produce, varieties WHERE produce.id = varieties.fk_fruit_id";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$produce_fruit_code = "";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($produce_fruit_code != $row['fruit_code'])
{
$produce_fruit_code = $row['fruit_code'];
echo "<br/>".$produce_fruit_code." - ". $row['variety_name'];
} else {
echo ", ".$row['variety_name'];
}
}
关于php - 用php分组查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10050220/