如何在此查询中获取具有用户ID的用户名? (MySQL的)

时间:2011-11-23 04:01:59

标签: mysql

我已经找到了大部分SQL查询,但我似乎需要一点帮助。

我似乎无法弄清楚如何使用usernameuser中选择social_posts.user_id

这是我的查询(有效):

SELECT social_posts.user_id, social_posts.post_stamp, social_posts.message
FROM social_posts
WHERE id IN (
SELECT social_threads.id 
FROM social_threads, friends 
WHERE (((friends.user_a = ?) || (friends.user_b = ?)) && (friends.request = 1)) || (social_threads.user_id = ?)
ORDER BY social_threads.id DESC)
LIMIT 15

我希望查询返回user.username。在user表中,用户ID称为id

当我尝试以下操作时出现错误:

SELECT social_posts.user_id, social_posts.post_stamp, social_posts.message, user.username
FROM social_posts
INNER JOIN user ON social_posts.user_id = user.id

WHERE id IN (
SELECT social_threads.id 
FROM social_threads, friends 
WHERE (((friends.user_a = ?) || (friends.user_b = ?)) && (friends.request = 1)) || (social_threads.user_id = ?)
ORDER BY social_threads.id DESC)

LIMIT 15

该查询返回以下错误: Column 'id' in IN/ALL/ANY subquery is ambiguous

虽然这有效:

SELECT social_posts.user_id, social_posts.post_stamp, social_posts.message, user.username
FROM social_posts
INNER JOIN user ON social_posts.user_id = user.id
LIMIT 15

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT social_posts.user_id, social_posts.post_stamp, social_posts.message, user.username
FROM social_posts , user
WHERE social_posts.id IN (
SELECT social_threads.id 
FROM social_threads, friends 
WHERE (((friends.user_a = ?) || (friends.user_b = ?)) && (friends.request = 1)) || (social_threads.user_id = ?)
ORDER BY social_threads.id DESC)
AND social_posts.user_id = user.id
LIMIT 15

我假设Order By子句是内部查询,