0

I'm creating two tables and I would like to use UserID in User_info_table as a foreign key in the Trail_info_table, but it keeps showing as NULL.

CREATE TABLE CW2.User_info_table
(
    UserID int IDENTITY PRIMARY KEY,
    User_name varchar(255),
    Email_Address varchar(255) NOT NULL,
    User_password varchar(255) NOT NULL,
    User_access_level int NOT NULL,
);

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Grace Hopper', 'grace@plymouth.ac.uk', 'ISAD123!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Tim Berners-Lee', 'tim@plymouth.ac.uk', 'COMP2001!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Ada Lovelace', 'ada@plymouth.ac.uk', 'insecurePassword', 1)



CREATE TABLE CW2.Trail_info_table
(
    TrailID int IDENTITY,
    Trail_name char(255) NOT NULL,
    Trail_owner varchar(255),
    Trail_owner_ID int 
        FOREIGN KEY REFERENCES CW2.User_info_table(UserID),
    Trail_difficulty int NOT NULL,
    Trail_length int NOT NULL,

    CONSTRAINT Trail_primary PRIMARY KEY (TrailID),
);

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Spring Sprint', 'Grace Hopper', 1, 10)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Summer Stroll', 'Tim Berners-Lee', 2, 15)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Winter Waltz', 'Ada Lovelace', 3, 20)

I tried to get the UserID (1,2,3) in the Trail_owner_ID column as a foreign key but it keeps showing up as NULL

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • What is your expectation? the dbms will not automatically find a UserId from User_Info_table, and insert it into Trail_info_table.Trail_owner_ID. You have to set those yourself!. You can change your inserts to the latter to use a select from the former. – tinazmu Jan 10 '23 at 02:56
  • Also, if Trail_owner is the user name then you should be getting this from the user table via a join (in any select statement) rather duplicating the same value in two tables – NickW Jan 10 '23 at 08:26

0 Answers0