大家好,我想显示一个表,以便该表具有2个外键。我的 food 和 restaurant 表具有 name 列。尝试遵循以下代码,但我不知道如何显示不同的餐厅名称和食物名称。
$sql_select_food = "SELECT food.id,restaurant.name,food.name,food.restaurant_id,foodcategory.title from food INNER join foodcategory ON food.foodcategory_id=foodcategory.id INNER join restaurant ON food.restaurant_id=restaurant.id WHERE food.isActive = 1 ORDER BY food.updateDate DESC";
$result_select_food = mysqli_query($connection, $sql_select_food);
if (mysqli_num_rows($result_select_food) > 0) {
while ($row_select_food = mysqli_fetch_assoc($result_select_food)) {
echo "
<tr>
<td>$row_select_food[name]</td>
<td>$row_select_food[name]</td>
<td>$row_select_food[title]</td>
</tr>
";
}
}
答案 0 :(得分:2)
使用列别名:
SELECT food.id AS food_id, restaurant.name AS restaurant_name, food.name AS food_name ...
然后
$row_select_food['restaurant_name']
是餐厅的名称,$row_select_food['food_name']
是食物的名称,注意:AS
关键字是可选的。
答案 1 :(得分:1)
为列名添加别名,然后在代码中稍后将其作为列名调用:
$sql_select_food = "SELECT food.id,restaurant.name as rname, food.name as fname, food.restaurant_id,foodcategory.title from food INNER join foodcategory ON food.foodcategory_id=foodcategory.id INNER join restaurant ON food.restaurant_id=restaurant.id WHERE food.isActive = 1 ORDER BY food.updateDate DESC";
$result_select_food = mysqli_query($connection, $sql_select_food);
if (mysqli_num_rows($result_select_food) > 0) {
while ($row_select_food = mysqli_fetch_assoc($result_select_food)) {
echo "
<tr>
<td>$row_select_food[rname]</td>
<td>$row_select_food[fname]</td>
<td>$row_select_food[title]</td>
</tr>
";
}
}