Search code examples
sqlpostgresqlinsertcreate-table

Create and insert data with many to many relationaships


I try one to many relationships in postgresql, but nothing

Here my wrong attempt

CREATE TABLE person_basic_info (
    id                                    INT           NOT NULL PRIMARY KEY,
    gender                                VARCHAR (50)  NULL,
    first_name                            VARCHAR (150) NULL,
    last_name                             VARCHAR (150) NULL,
    email                                 VARCHAR (50)  NULL,
    political_view_id                     INT           NULL,
    cambridge_analytica_psychographics_id INT           NULL REFERENCES persons_features (id),
    revolution_sympathy                   int           NULL,
    iq_level                              INT           NULL
);

Create person features

CREATE TABLE persons_features (
    id               INT            NOT NULL PRIMARY KEY,
    dominate_feature VARCHAR (100) NULL
);


--person_basic_info

insert into person_basic_info(id, gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (1,'Female','Corenda','Garrood','cgarrood0@yellowbook.com',6,2,0,86);
insert into person_basic_info(id,gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (2,'Male','Langston','McMychem','lmcmychem1@theatlantic.com',2,4,0,111);
insert into person_basic_info(id,gender, first_name, last_name, email, political_view_id, cambridge_analytica_psychographics_id,revolution_sympathy,iq_level) values (3,'Female','Robbyn','Imison','rimison2@geocities.com',14,3,1,98);


--persons_features
insert into persons_features (id, dominate_feature) values (1,'Agreeableness');
insert into persons_features (id, dominate_feature) values (2,'Conscientiousness');
insert into persons_features (id, dominate_feature) values (3,'Extraversion');
insert into persons_features (id, dominate_feature) values (4,'Neuroticism');
insert into persons_features (id, dominate_feature) values (5,'Openness');

But nothing.

Could you help me?


Solution

  • If you execute this queries in proper order, you will get no error at all. The proper order in this case should be:

    1. CREATE TABLE persons_features
    2. CREATE TABLE person_basic_info
    3. insert into persons_features
    4. insert into person_basic_info

    In this case, this isn't many to many relationship, unless person can have more than one value of cambridge_analytica_psychographics_id. If so, you should create intersection table instead of reference to persons_features table.