在 SQL 中同步跨表的 N 个值
免责声明:我刚刚开始使用数据库,所以我可能错过了一些非常微不足道的东西。
我有两个(有些相关,但不足以成为单个表)表:table_one
和 table_two
。
table_one
有两列重要的内容:
name
类型为varchar(n)
intersects
类型为bit< /code>
table_two
有一列重要:
name
类型为varchar(n)
我想自动将 intersects
设置为 0
或 1
,具体取决于 name
是否出现在 table_two
中。
我可以以某种方式将这个责任委托给数据库引擎吗? 我目前正在使用 MySQL,如果这很重要的话。
编辑:在处理数据库时这种紧密耦合是否有意义?
Disclaimer: I just started with databases, so I'm probably missing something extremely trivial.
I have two (somewhat related, but not enough to be a single table) tables: table_one
and table_two
.
table_one
has two columns of significance:
name
of typevarchar(n)
intersects
of typebit
table_two
has one column of significance:
name
of typevarchar(n)
I would like to automatically set intersects
to either 0
or 1
depending on whether name
is present in table_two
.
Can I somehow delegate this responsibility to the database engine? I'm currently using MySQL, if that matters.
EDIT: Does this sort of close-coupling even make sense when dealing with databases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ANSI SQL:
MySQL Join:
您可以将此查询放入 < code>trigger 使
intersects
保持最新:现在,对于设计讨论:
intersects
列很棒,但是您可能会遇到不同步的问题。 您可以做的是在调用此函数时在select
中使用exists
函数:您可以使用
notexists
来查找不相交的那些,还有。此外,您还可以使用
left join
来拉回这两种情况:任何
t2.name
为null
的情况,您都没有路口。 任何不存在的地方,你都会做。 当然,如果您对name
没有unique
约束,这可能会产生重复的行。希望这能为所有这一切带来一些启发!
ANSI SQL:
MySQL Join:
You can put this query into a
trigger
to keepintersects
up-to-date:Now, for the design discussion:
An
intersects
column is great and all, but you may run into the issue where it gets out of sync. What you can do is use anexists
function in yourselect
when calling this:You can use
not exists
to find those that don't intersect, as well.Moreover, you can also use a
left join
to pull back both cases:Anything where
t2.name
isnull
, you don't have an intersection. Anything where it isn't, you do. Of course, this can produce duplicate rows if you don't have aunique
constraint onname
.Hopefully this sheds some light on all of this!