2

Maybe this is a stupid question, but I'm kind of stuck here... So I have a table A

state | city
MI     Detroit
... 

And I have a state table B

state_id | state
1           MI
...

And a city table C

city_id | city | state_id
1        Detroit  NULL

I want to add a foreign key column in city table, I've already created a foreign key column in it with the syntax ALTER TABLE city ADD CONSTRAINT city_state FOREIGN KEY (state_id) REFERENCES state(state_id); But the foreign key column was filled with null since it doesn't know the relation between city table and the state table.

How can I fill in the foreign key column with right state id? Can someone help?

4
  • Please clarify your question. What is the newly created foreign key column? A foreign key is a constraint on what data you can store, it doesn't create any new columns or data. Also, your tags are conflicting (mysql & postgresql). Commented Dec 1, 2018 at 1:34
  • I've updated the question. The city table should be city_id, city, state_id. But with the above ALTER TABLE syntax the state_id column is only filled with NULL Commented Dec 1, 2018 at 1:37
  • Tag your question with the database you are really using. Commented Dec 1, 2018 at 1:39
  • Now your design doesn't make much sense. I'd think you'd want one table with (state_id, state) and one table (city, state_id). Commented Dec 1, 2018 at 1:51

2 Answers 2

3

You can use join in an update. In Postgres this looks like:

update city
   set state_id = b.state_id
   from a join
        b
        on a.state = b.state
   where city.city = a.city;

In MySQL:

update city join
       a
       on city.city = a.city join
       b
       on a.state = b.state
   set city.state_id = b.state_id;
Sign up to request clarification or add additional context in comments.

Comments

-1

You SQL code for Mysql is:

CREATE TABLE city (
    city_id int NOT NULL,
    name varchar(255) NOT NULL,
    state_id int,
    PRIMARY KEY (city_id),
    FOREIGN KEY (state_id) REFERENCES state(state_id)
);

And if you want add a new row with a reference to another row in the state`s table, you need add the id of this row, example:

INSERT INTO city VALUES  (1, "Los Angeles", 1);

1 will be a id from state table!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.