开发者

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

开发者 https://www.devze.com 2022-12-10 09:23 出处:网络
Users Table user_idusernamethumb_idfullimage_id 1jprescott1415 2lpausch1819 Images Table image_idpath 14jprescott/small.jpg

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          msamue开发者_StackOverflow中文版ls/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.


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


How about:

select u.username, i1.path, i2.path from users u, images i1, images i2 
  where u.user_id = ? and u.thumb_id = i1.image_id and u.fullimage_id = i2.image_id
0

精彩评论

暂无评论...
验证码 换一张
取 消