如何设计 table 方便的插入和 select, 好的设计

how to design the table convenient insert and select,and good design

我要统计访问信息数据,信息有两种不同table, 我设计 table 使用类型区分不同 table, 比如

CREATE TABLE visitor(
visitorId BIGINT UNSIGNED NOT NULL,
informationId BIGINT UNSIGNED NOT NULL,
visitCount BIGINT UNSIGNED NOT NULL,
type -- "news" or "tech"
PRIMARY KEY (visitorId , informationId ),
);

我知道它是多态关联,table不遵循3NF, 传递依赖是指一个非关键字段的值依赖于另一个 非关键字段的值。 type 列取决于 visitedInformation, 我尝试拆分 table,

CREATE TABLE newVisit (
informationId BIGINT UNSIGNED NOT NULL,
visitorId BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (issue_id, comment_id),
FOREIGN KEY (informationId) REFERENCES news(id),
FOREIGN KEY (visitorId) REFERENCES Visitor(id)
);

CREATE TABLE newVisit (
informationId BIGINT UNSIGNED NOT NULL,
visitorId BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (issue_id, comment_id),
FOREIGN KEY (informationId) REFERENCES news(id),
FOREIGN KEY (visitorId) REFERENCES Visitor(id)
);

CREATE TABLE visitor(
visitorId BIGINT UNSIGNED NOT NULL,
informationId BIGINT UNSIGNED NOT NULL,
visitCount BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (visitorId , informationId ),
);

但是外键visitorId,无法识别访客所在的行, 我应该使用 table 设计吗?

CREATE TABLE newVisit (
informationId BIGINT UNSIGNED NOT NULL,
visitorId BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (issue_id, comment_id),
foreign key (informationId , visitorId ) 
    references visitor(informationId , visitorId ),
);

我觉得table插入数据不方便,我必须加入newVisit和visitor才能插入,但如果我使用第一种设计,我只加入一个table。

据我所知,您有两个实体 table,访客和新闻。现在你想追踪……到底是什么?哪些新闻...项目?...每个访问者访问?听起来不祥。

如果这是正确的,那么您希望将许多访问者与许多新闻相关联。这是一个简单的交集 table:

create table NewsVisits(
    VisitorID  int  not null,
    InfoID     int  not null,
    VisitCount int  not null default 1, -- to allow same visitor to access same info many times???
    constraint  PK_NewsVisits primary key( VisitorID, InfoID ),
    constraint  FK_NewsVisits_Visitor foreign key( VisitorID )
        references Visitors( ID ),
    constraint  FK_NewsVisits_Info foreign key( InfoID )
        references News( ID )
);

因此,当访问者访问新闻项时,插入该信息——除非该访问者已经访问过该新闻项,在这种情况下,您会增加访问次数。