在sqlite中模拟变量列名
我想在数据库中存储条目(一组键=>值对),但键因条目而异。
我想存储两个表,(1)每个条目的键和(2)每个条目的特定键的值,其中条目在两个表中共享一个公共 id 字段,但我不知道如何提取具有此类配置的 sql 中的条目作为 key=>value 对。
有更好的方法吗?如果这在 sqlite 中不可能,那么在 mysql 中可以吗?谢谢!
I want to store entries (a set of key=>value pairs) in a database, but the keys vary from entry to entry.
I thought of storing with two tables, (1) of the keys for each entry and (2) of the values of specific keys for each entry, where entries share a common id field in both tables, but I am not sure how to pull entries as a key=>value pairs in sql with this sort of configuration.
Is there a better method? If this is not possible in sqlite, is it possible in mysql? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您正在寻找 Entity-Attribute-Value 模型。
替代方法是为不同类型的实体创建不同的表,或者为每个可能的键创建一个包含一列的表,并将没有该键的实体的值设置为 NULL。
您可能想看看 Bill Karwin 的演示SQL 反模式,其中他介绍了 EAV 模型的一些优缺点,并提出了可能的替代方案。相关部分从幻灯片 16 开始。
It sounds like you are looking for the Entity-Attribute-Value model.
Alternatives are to create different tables for different types of entities, or to have a table with a column for every possible key and set the value to NULL for entities that don't have that key.
You might want to take a look at Bill Karwin's presentation SQL Antipatterns where he covers some of the pros and cons of the EAV model and suggests possible alternatives. The relevant part starts from slide 16.
@Mark Byers 是对的,这就是 EAV 模型。在你陷入黑暗之前,你应该阅读Bad CaRMa小路。这是一个关于数据库设计如何摧毁一家公司的故事。
在关系数据库中,关系中的每一行都必须包含相同的列。这是关系定义的一部分。这在 SQLite、MySQL 或任何其他关系数据库中都是如此。
另请参阅我的演示文稿 SQL 中的实用面向对象模型 或我的书 SQL Antipatterns,其中我展示了由EAV 模型。
如果每个实体需要变量列,则需要非关系数据库。有一些面向文档的数据库,例如 CouchDB 或 MongoDB 正在流行。
或者,如果您想要嵌入式单用户,请尝试 Berkeley DB像 SQLite 这样的解决方案。
@Mark Byers is right, this is the EAV model. You should read Bad CaRMa before you go down that dark path. It's a story of how this database design practically destroyed a company.
In a relational database, every row in a relation must include the same columns. That's part of the definition for a relation. This is true in SQLite, MySQL, or any other relational database.
Also see my presentation Practical Object-Oriented Models in SQL or my book SQL Antipatterns, in which I show the problems caused by the EAV model.
If you need variable columns per entity, you need a non-relational database. There are document-oriented databases like CouchDB or MongoDB that are catching on in popularity.
Or try Berkeley DB if you want an embeddable single-user solution like SQLite.