[英]SQL - Select data from three tables where one table has multiple foreign keys to the same primary key
I have the following tables and relations: 我有以下表格和关系:
When I create a User
, that user gets a CurrentWeek
row and that current week row in turn gets a CurrentWeekStatus
row. 当我创建一个User
,该用户获得一个CurrentWeek
行,而该当前周又获得一个CurrentWeekStatus
行。 The user can add food items to the Food
table and then can choose from these food items and select a few to insert in CurrentWeek
. 用户可以将食物添加到“ Food
表中,然后可以从这些食物中进行选择,然后选择一些要插入到CurrentWeek
。
In the client I want to grab CurrentWeek
as an object that has a list of Food
objects and a list of their corresponding status. 在客户端中,我想将CurrentWeek
用作具有Food
对象列表及其对应状态列表的对象。
I am struggling as to how to make this happen. 我正在努力实现这一目标。 I think this can be done by making multiple queries to the database, one to fetch CurrentWeek
and then from this extract all the FoodId
's and make separate queries to fetch each Food
. 我认为可以通过对数据库进行多个查询来完成此操作,一个查询要获取CurrentWeek
,然后从中提取所有FoodId
并进行单独的查询以获取每个Food
。 But this seems like a very bad solution. 但这似乎是一个非常糟糕的解决方案。
The other solution I can think of is making a view with all the necessary data. 我能想到的另一种解决方案是使用所有必要的数据进行查看。 But I don't know how to make this view and even if I manage to make the view I don't know how to separate each Food
into different objects. 但是我不知道如何制作这种视图,即使我设法完成了该视图,我也不知道如何将每种Food
分成不同的对象。
Do anyone know of a good way to accomplish this? 有人知道实现此目标的好方法吗?
I use NodeJs as a REST API and Android Studio with retrofit to send REST calls. 我将NodeJ用作REST API,并使用经过改进的Android Studio发送REST调用。
After consulting StackOverflow and a few colleagues I changed the initial database schema into: 在咨询了StackOverflow和一些同事之后,我将初始数据库架构更改为:
This was a design I initially chose to not go with as I thought adding one row on the CurrentWeek
table for each user would be better than to add many rows for each user in the PlannedFood
table. 这是一个设计,我最初选择不与我想象中的添加一行去CurrentWeek
表中的每个用户会更好,而不是添加许多行中的每个用户PlannedFood
表。 I see now however that this design have a few advantages as compared to the other design. 但是,我现在看到该设计与其他设计相比具有一些优势。
Designing it this way also solves my initial question as I can now grab all the rows in PlannedFood
for a specific user, joining on FoodId
and then map the Food
data into a Food
object on client-side. 以这种方式设计它还解决了我的第一个问题,因为我现在可以为特定用户抓取PlannedFood
中的所有行,加入FoodId
,然后将Food
数据映射到客户端上的Food
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.