同一个表的两个外键。我该如何编写这个SELECT语句?

时间:2009-10-31 22:12:49

标签: sql mysql

用户表

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

图像表

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

现在,如何编写SELECT语句以检索具有thumb和fullimage路径的用户?问题是同一个表中有两个外键。

2 个答案:

答案 0 :(得分:19)

你做两个连接:

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

答案 1 :(得分:0)

怎么样:

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