Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: how to replace foreign key column with data from referenced table?

I have 2 tables, let's call 'm Table-A and Table-B. Table-A contains a FK referencing Table-B. I don't need Table-B anymore, but I do need to keep 1 column from Table-B. So, I want to replace all foreign-keys in Table-A with the data from a single column in the referenced row in Table-B. So I'm wondering, is there a SQL query I can use to perform that action?

It's just a simple sqlite database, if that matters.

To make a bit more clear, here's an 'illustrated' example:

Current situation:

TABLE-A:
ID    COL1    COL2    COL3(FK)
-------------------------------
1     text    text    13
2     text    text    14

TABLE-B:
ID    COL4    COL5    COL6
-------------------------------
13    rice    sushi   pizza
14    pasta   fries   chips

Wanted situation:

TABLE-A:
ID    COL1    COL2    COL3
-------------------------------
1     text    text    pizza
2     text    text    chips
like image 547
Landcross Avatar asked Feb 05 '17 10:02

Landcross


People also ask

How do you change a foreign key reference in a table?

Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!

Is it possible to have a table that has a foreign key that references the same table?

FOREIGN KEY constraints can reference another column in the same table, and is referred to as a self-reference. A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.


2 Answers

Yes. It's called JOIN.

select
    a.id,
    a.col1,
    a.col2,
    b.col6 col3
from tablea a join tableb b
on a.col3 = b.id;
like image 123
Gurwinder Singh Avatar answered Sep 30 '22 02:09

Gurwinder Singh


If is just a query, GurV's answer is good. If it's something you will use a lot, then i suggest to create a view :

CREATE VIEW tablec AS
SELECT a.id, a.col1, a.col2, b.col6 AS col3
FROM tablea a, tableb b
WHERE a.col3 = b.id

(sorry, i'm an oldschool SQL developper :))

And now just use :

SELECT * FROM tablec
like image 27
Stv Avatar answered Sep 30 '22 02:09

Stv