简体   繁体   English

联结表中的额外user_id为简单起见

[英]Extra user_id in junction table for simplicity

I have 3 tables: 我有3张桌子:

foo(id, ..., user_id)
bar(id, ...)
foo_bar(foo_id, bar_id)

I need to select a row from 'foo_bar' and check if the record belongs to a specific user. 我需要从“ foo_bar”中选择一行,并检查记录是否属于特定用户。 Is it good practice to add a 'user_id' column to 'foo_bar' table so that I could run a query: 将“ user_id”列添加到“ foo_bar”表是一种好习惯,这样我就可以运行查询:

// 1 query only 
$foobar = SELECT * FROM foo_bar WHERE foo_id = ? AND bar_id = ? AND user_id = ?

instead of first querying 'foo' table to check if 'foo' record belongs to user and then running a second query to select the 'foo_bar' record? 而不是先查询“ foo”表以检查“ foo”记录是否属于用户,然后运行第二个查询以选择“ foo_bar”记录? Something like this: 像这样:

// 2 queries
$userId = SELECT user_id FROM foo WHERE foo_id = ?;
if ($userId === $userIdToCompareTo) {
    $foobar = SELECT * FROM foo_bar WHERE foo_id = ? AND bar_id = ?
}

Does this make sense or is this usually handled another way with a more complex query? 这有意义吗,或者这通常是通过更复杂的查询以另一种方式处理的吗?

No, you should not. 不,你不应该。 You should look up the value using a join : 您应该使用join查找值:

select . . . 
from foo_bar fb join
     foo f
     on fb.foo_id = f.id
where f.user_id = ?;

A key principle of data modeling is that you should store data in only one place. 数据建模的关键原则是,您应仅将数据存储在一个位置。 That is, if you store the user_id in foo_bar , then what happens if the user_id changes? 也就是说,如果将user_id存储在foo_bar ,那么如果user_id更改会怎样? Or if the foo record is deleted? 还是如果foo记录被删除?

There are some situations where you would want to replicate the user id. 在某些情况下,您需要复制用户ID。 In particular, if the user id does change, you might want to capture the user_id on foo_bar at the moment when the record is created. 特别是,如果用户ID 确实发生了变化,那么您可能希望在创建记录时在foo_bar上捕获user_id I only bring this up because it is important to understand principles and to understand when they don't necessarily apply. 我之所以提出这一点,是因为重要的是要理解原理并了解它们何时不一定适用。

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

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