如何将来自多行的数据放入MySQL中的一个行数组中

时间:2014-10-17 21:11:48

标签: mysql

假设我有一个表days,它使用指向包含食物名称的表food的ID来指定每天的早餐食物和晚餐食物。如何使用单个查询获取早餐和晚餐食品名称?基本上我想将以下内容合并到一个查询中:

SELECT days.*, food.name AS breakfast_name FROM days, food WHERE days.breakfast_id = food.id AND days.id = '12'
SELECT days.*, food.name AS dinner_name FROM days, food WHERE days.dinner_id = food.id AND days.id = '12'

1 个答案:

答案 0 :(得分:1)

您可以通过在单独的ID上连接两次食物表来在单个查询中执行此操作。

SELECT days.*, bf.name AS breakfast_name, df.name AS dinner_name FROM days JOIN food AS bf ON days.breakfast_id=bf.id JOIN food AS df ON days.dinner_id=df.id;