【问题标题】:SQL - table having different values for different points in time - best practise?SQL - 在不同时间点具有不同值的表 - 最佳实践?
【发布时间】:2017-11-20 12:47:20
【问题描述】:

我目前正在设计一个数据库,用于记录特定时间范围内的一些值。为了说明起见,假设我有一个表,其中包含以下列作为主键:

姓名 |一些整数 |另一个整数

我想为同一个主键记录不同的值,例如 30 秒。例如,可能有多个记录具有相同的“Name”、“SomeInteger”、“AnotherInteger”,其中只有“Timestamp”保证与其他记录不同。

“示例名称”| 1 | 3 |时间戳1 | Value1
“示例名称”| 1 | 3 |时间戳2 | Value2
“示例名称”| 1 | 3 |时间戳3 |价值3 ...

这意味着我会将 Timestamp 列作为主键的一部分。我目前想知道这样做的最佳数据库设计(或最佳实践)是什么?我应该只包含一个时间戳列作为主键的一部分还是有更好的解决方案?

提前非常感谢您。 英戈

【问题讨论】:

    标签: mysql sql database sqlite crud


    【解决方案1】:

    同一个主键可能有多个记录,例如:

    你似乎很困惑。根据定义,主键是唯一的。您的表很好,但主键(如所述)是复合主键。

    您似乎需要两张桌子。一个是你的实体:

    create table entity (
        EntityId int auto_increment primary key,
        Name varchar(255) not null,
        someInteger int not null,
        anotherInteger int not null,
        unique (name, someInteger, anotherInteger)
    );
    
    create table entityValues (
        entityValueId int auto_increment primary key,
        EntityId int,
        timestamp datetime,
        value ?,  -- I don't know what the type is
        foreign key (EntityId) references entities(EntityId)
    );
    

    这使用 MySQL 语法。你可以在 SQLite 中做同样的事情。

    【讨论】:

    • 哦,是的,你是对的。我不知何故忘了提到我想将时间戳作为主键的一部分,然后让它再次唯一。我将编辑问题。
    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 2023-01-18
    • 2021-11-02
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多