如何实现mySQL自我关系?

Cip*_*hor 1 mysql sql database-relations self

如何Message在mySQL中创建一个表格来存储消息及其响应?

在此输入图像描述

Pab*_*ruz 6

你可以试试这个:

create table messages (
    message_id int primary key,
    response_to int null references messages(message_id), -- self relationship
    user_from int not null references users(user_id),
    user_to int not null references users(user_id),
    content varchar(200) not null
);
Run Code Online (Sandbox Code Playgroud)

第一条消息将具有null值un response_tofield.

作为旁注,如果您计划存储"对话"而不是"消息",请考虑使用CLOB(字符大对象)的普通表来存储对话的JSON或XML表示.它将加快您的查询速度(如果您总是计划一次阅读整个会话而不是单个消息).