Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to join multiple foreign keys to same table

Tags:

sql

join

mysql

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
like image 484
Adam Meyer Avatar asked Jul 20 '11 02:07

Adam Meyer


People also ask

Can you have multiple foreign keys to the same table?

A table can have multiple foreign keys based on the requirement.

Can you link 2 foreign keys?

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.

Are joins faster with foreign keys?

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.


1 Answers

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
like image 165
mu is too short Avatar answered Sep 29 '22 19:09

mu is too short