【发布时间】:2019-01-17 03:54:38
【问题描述】:
【问题讨论】:
标签: sql database postgresql database-design
【问题讨论】:
标签: sql database postgresql database-design
执行此操作的标准 SQL 方法是使用 2 个表
create table routine (
id serial primary key,
name text
);
create table exercises (
routine_id integer references routine(id) on delete cascade /*optional*/,
exercise text
);
Postgres 提供了一种很好的语法(尽管不是 100% 标准),可以在 1 中通过练习创建例程:
with new_routine_id as (
insert into routine(name)
values ('Chest')
returning id
)
insert into exercises
select id, unnest(array['Bench Press', 'Skull Crusher', 'Incline Bench Press'])
from new_routine_id
选择如你所愿:
select id, name, array_agg(exercise order by exercise /*it could be ordered using an additional field*/) as exercises
from routine
join exercises on id = routine_id
group by id, name
修改 @klin 发布了一个替代解决方案,其中包含 1 个表,其中包含一个直接用于练习的数组。该解决方案完全有效,并且在某些方面比我的更简单(毕竟我在第一条评论中很快提到了这个解决方案)。
恕我直言,一个解决方案比另一个“更好”的原因有一个。您是否在一个每个人都知道如何处理数组的团队中工作?
JOIN 即可完成您需要的所有操作,无需数组。【讨论】:
ARRAY 列进行练习,但就个人而言,我不喜欢这样做。
exercises 没有 UNIQUE 约束也没有主键。我不确定是用一个完整的定义明确的模式来回答更好,还是简单地用任何能涵盖这个问题的最少的东西来回答会更好。我选择了后者。
我知道您不应该对 SQL 数据库使用列表...
这在现代数据库中并不明显。 Arrays in Postgres 实现得非常好,可能会让生活更轻松。关系方法described by @lau没有错,但你也可以考虑这样的简单结构
create table routines (
id serial primary key,
name text,
exercises text[]
);
请阅读Is it bad design to use arrays within a database? 以获取更多信息,以帮助您做出正确的决定。还有,关注这个tip from the documentation
数组不是集合;搜索特定的数组元素可能是数据库设计错误的标志。考虑使用一个单独的表,其中每个项目将是一个数组元素。这将更容易搜索,并且对于大量元素可能会更好地扩展。
【讨论】: