Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign keys of the same table. How do I write this SELECT statement?

Tags:

sql

mysql

Users Table

user_id    username    thumb_id    fullimage_id
1          jprescott   14          15
2          lpausch     18          19

Images Table

image_id    path
14          jprescott/small.jpg
15          jprescott/big.jpg
16          msamuels/small.jpg
17          msamuels/big.jpg
18          lpausch/small.jpg
19          lpausch/big.jpg

Now, how do I write a SELECT statement to retrieve a user with the thumb and fullimage paths? The issue is that of having two foreign keys of the same table.

like image 974
HyderA Avatar asked Oct 31 '09 22:10

HyderA


1 Answers

You do two joins:

SELECT u.username, i1.path AS thumb, i2.path AS full
  FROM users AS u
    JOIN images AS i1 ON u.thumb_id = i1.image_id
    JOIN images AS i2 ON u.fullimage_id = i2.image_id
like image 81
Ayman Hourieh Avatar answered Oct 08 '22 17:10

Ayman Hourieh