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
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!
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With