简体   繁体   English

我应该在表格中创建一个新字段,还是只选择第二个表格的MAX

[英]Should I create a new field in the table or just select the MAX of the second table

On this question I received an answer that worked well. 在这个问题上,我收到了一个运作良好的答案。 I am now wondering if there is a possible better structure. 我现在想知道是否有更好的结构。

I have two tables. 我有两张桌子。

Projects : id, title
Status : project_id, status_id, created(DATETIME)

At the moment to get the status of my project, I get the project ID and pull the latest row out of the status table based on the project id. 在获取项目状态的那一刻,我获得了项目ID,并根据项目ID从状态表中提取最新行。 To get this latest row is quite a hassle. 获得这一最新行非常麻烦。

Should I rather change the schema to this? 我应该更改模式吗?

Projects : id, title, current_status_id(FK)
Status : id(PK), project_id, status_id, created(DATETIME)

Then I can just join the tables with the FK and get the row that I want without looking for the latest? 然后我可以加入FK的表格并获得我想要的行,而不是寻找最新的?

EDIT : 编辑

So I want something like this 所以我想要这样的东西

SELECT * FROM projects
LEFT JOIN status on projects.id = status.project_id
WHERE projects.id = 1

But I want only the latest record in the status table. 但我只想要状态表中的最新记录。

EDIT 2 : 编辑2

So I want something like this 所以我想要这样的东西

SELECT * FROM projects
LEFT JOIN status on projects.id = status.project_id

But for each project returned, only get the latest status record for that project_id from status. 但是对于返回的每个项目,只从状态获取该project_id的最新状态记录。

How is this a hassle? 这有什么麻烦?

SELECT project_id, status_id, created 
FROM Status 
WHERE project_id = the-id
ORDER BY created DESC
LIMIT 1;

Or, if you need a list of multiple projects: 或者,如果您需要多个项目的列表:

SELECT a.project_id, a.status_id, a.created 
FROM Status a
LEFT JOIN Status b
ON a.project_id = b.project_id
AND b.created > a.created
WHERE a.project_id IN(id1, id2, id3) AND b.project_id IS NULL;

So, with project data: 所以,有了项目数据:

SELECT Projects.*, Status.*
FROM Projects
LEFT JOIN Status 
ON Status.project_id = Projects.id
WHERE Projects.id = the-id
ORDER BY Status.created DESC
LIMIT 1;

Or: 要么:

SELECT Projects.*, Status.*
FROM Projects
LEFT JOIN Status a
ON a.project_id = Projects.id
LEFT JOIN Status b
ON a.project_id = b.project_id
AND b.created > a.created
WHERE b.project_id IS NULL;

That's one way to do it. 这是一种方法。

You might not even need the current_status field to be an FK; 您甚至可能不需要current_status字段作为FK; why not just store the value? 为什么不只是存储价值? You could get into odd circular references otherwise. 否则你可以进入奇怪的循环引用。

Another way would be to store a status archive, separate of the projects table. 另一种方法是存储状态存档,与项目表分开。 Every time the status changes, insert the current status into the archive table, and change the projects.status value. 每次状态更改时,将当前状态插入存档表,并更改projects.status值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM