【问题标题】:Add Unordered List of items in database?在数据库中添加项目的无序列表?
【发布时间】:2020-02-27 09:42:39
【问题描述】:

我正在尝试构建一个包含多个列的字符串内容表,其中一些列包括(项目符号)无序列表。这被认为是一个值列表、一个数组还是其他东西?这是一个例子:

|----|----------------------|----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| 1 | Transition Age Youth | • Wrap-around services • Case management • Voluntary residential services • Employment and permanent housing support | • Outreach and engagement  • Telemedicine  • Counseling and services |```

Is this as simple as using line breaks /n or /r/n in the data itself? 

I'll be using this as an open-data directory of services. I intend to have a search function where people can find all records containing keywords they specify. There's about 10 more columns I'm not showing which would help others narrow by filtering rows. 

Thank you for any insight. 

[!This photo illustrates one of several tables. Some have multiple unordered lists, this one illustrates a single list. There may be a limited list of options if that would help knowing too.[1]][1]


  [1]: https://i.stack.imgur.com/MaTmV.png

【问题讨论】:

  • 在考虑如何存储列表之前,您应该准备好解释处理它的所有方式。您是否要动态地将元素添加到列表中?每个列表项是否与其他数据相关,例如您要执行基于文本的搜索吗? Tim 的“将列表项标准化为表格”方法是教科书式的,但仅当每个列表项都与数据相关时才适用。这些可能更像标签,甚至是任意内容?

标签: arrays postgresql html-lists


【解决方案1】:

项目符号分隔(或任何文本分隔符分隔)的值通常表示未规范化的数据,您应该避免将其存储在数据库中。我建议以下设计:

id | idx | desc
1  | 1   | Prevent re-institutionalization and homelessness;
1  | 2   | Transition Age Youth
1  | 3   | Wrap-around services
1  | 4   | Case management
1  | 5   | Voluntary residential services

如果你想生成一个项目符号分隔的列表,只需使用 Postgres 的string_agg 函数:

SELECT
    id, 
    string_agg(desc, '•' order by idx) as list
FROM your_table
GROUP BY
    id;

【讨论】:

  • 需要your_table 和描述表之间的索引; OP 示例保留了这种关系
  • 感谢蒂姆。我的挑战是每条记录都有几列带有无序列表。我可以使用您建议的同一个表格并添加一个包含表格列名的列吗?
  • 我错过了list.id == desc.id 的限制吗?我还注意到这会创建一个项目符号 分隔 列表,这与每个列表元素都由项目符号 preceeded 的“项目符号列表”不太相同。有趣的是,您已经解决了这两个问题中较难的一个
  • 现在不确定您要的是什么。请编辑您的问题并向我们展示。
  • 永远不要将列名放在表格行中。这是一个明确的信号,表明您需要对数据进行非规范化。当数据之间存在特定且普遍的关系时,列是合适的。但是列表元素和它们的父项之间存在什么关系?所有项目都有相同的设置列表吗?或者那里有更动态的关系?
猜你喜欢
  • 2017-02-10
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多