在单个语句中创建表友的正确方法

问题描述 投票:0回答:1

我有表用户

CREATE TABLE IF NOT EXISTS users(
    id int AUTO_INCREMENT PRIMARY KEY,
    user_id INTEGER NOT NULL UNIQUE,
    goal VARCHAR(255) DEFAULT NULL,
    age INTEGER DEFAULT NULL,
    gender VARCHAR(255) DEFAULT NULL,
    country VARCHAR(255) DEFAULT NULL,
    city VARCHAR(255) DEFAULT NULL,
    comment VARCHAR(255) DEFAULT NULL)

我想创建表友。一个关键的功能,就是每个用户默认为自己加好友。

这是我目前的语句

create table friends (user_id int,  friend_id int, FOREIGN KEY (user_id) REFERENCES users (user_id), foreign key (friend_id) references users (user_id)) as select user_id from users;

update friends set shown_id = user_id;

我觉得这看起来挺笨拙的,创建一个表,马上就改,可能有更好的实现方式吗?

还有一个重要的问题:创建朋友表后,数据库失去连接。

create table friends (user_id int,  friend_id int, FOREIGN KEY (user_id) REFERENCES users (user_id), foreign key (friend_id) references users (user_id)) as select user_id from users;
ERROR: 2006: MySQL server has gone away
The global session got disconnected..
Attempting to reconnect to 'mysqlx://root@localhost:33060/test_db'....
The global session was successfully reconnected.
mysql sql
1个回答
0
投票

不知道 shown_id 是怎么来的,但我想这是一个排版错误。

与其只填充朋友表中的一列(user_id),不如在选择语句中添加另一列user_id别名为friend_id。不需要立即更新查询。

create table friends (
    user_id int,
    friend_id int,
    foreign key (user_id) references users (user_id),
    foreign key (friend_id) references users (user_id)
) as (
    select user_id, user_id as friend_id 
    from users
);

原始答案 https:/dba.stackexchange.coma266893208647。

© www.soinside.com 2019 - 2024. All rights reserved.