Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL动态结构_Sql_Postgresql - Fatal编程技术网

SQL动态结构

SQL动态结构,sql,postgresql,Sql,Postgresql,我有以下结构 construction id 1 building-step id construction_id step_id worker_id 1 1 1 1 1 1 2 2 step id name 1 foundation 2 wall 3 roof 使用样板添加新构造时,将生成建筑步骤。初始配置后,可以添加或删除步骤 要求之一是将构造模板显示为字符串。模板是

我有以下结构

construction
id
1

building-step
id construction_id  step_id     worker_id
1  1                1           1
1  1                2           2

step
id name
1  foundation
2  wall
3  roof
使用样板添加新构造时,将生成建筑步骤。初始配置后,可以添加或删除步骤

要求之一是将构造模板显示为字符串。模板是动态的,因为您可以添加和删除步骤。 在这种情况下,模板名称为“基础+墙”。如果我添加另一个建筑步骤,模板名称将为“基础+墙+屋顶”

我的问题是,如何以优化的方式实现这一点?
SQL结构是这种动态复杂性的问题吗?

在Postgres中,您可以使用
string\u agg
函数,该函数包含一行行字符串

在您的示例中,您可以尝试:

select string_agg(nm,'+') from(
    select st.name as nm
    from building-step bs
    inner join 
    step st
    on bs.step_id=st.id
    where bs.construction_id=1
    order by bs ASC
); --done by hand, may have small errors

它将随时支持在两个表中进行编辑,并将很好地执行。

代码是正确的,但是sql结构是否适合于要求?是的,它很好。如果所有id列还没有主键,则应该将它们添加到building_步骤(construction_id)中,这将有助于查询的where部分。除非您碰巧在行数较大的表上每天运行1000次此查询,否则它将正常工作。