I have a table "user" with a few rows that are both foreign keys for the same table "content" kinda like this:
user.id
user.bio
user.signature
content.id
content.text
I know this is not the right way to do this from a normalization standpoint, but the "content" table is from a separate DB that I cant modify. And I dont want to duplicate the data.
Im having a problem finding a good way to join them. All I have been able to do is this, but this seems wasteful.
SELECT bio.bio, text.text
FROM(
SELECT content.text as bio
FROM content, user
WHERE user.bio = content.id
AND user.id = 4) AS bio,
SELECT content.text as content
FROM content, user
WHERE user.signature = content.id
AND user.id = 4) AS content
A table can have multiple foreign keys based on the requirement.
In a word, yes. You can have as many foreign keys as you want referencing the same primary key. The recommended limit for the number of foreign keys in a table is 253.
Foreign keys do not directly speed up the execution of queries. They do have an indirect effect, because they guarantee that the referenced column is indexed. And the index will have an impact on performance. As you describe the problem, all the join relationships should include the primary key on one of the tables.
You can join one table multiple times if you give each instance a different alias:
SELECT bio.text, sig.text
FROM user u
JOIN content bio ON u.bio = bio.id
JOIN content sig ON u.signature = sig.id
WHERE u.id = 4
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