从三个表SQL中获取数据

时间:2012-01-24 19:45:00

标签: php mysql sql

我的MySQL表结构(3表)

用户

  

ID
  用户名

图片

  

ID
   USER_ID
  图像

user_follow

  

ID
  USER_ID
  follow_id

我尝试进行查询,从我的“images”表(user_id = 3)和我关注的朋友“user_follow”表中提供所有图像

现在查询并且它给了我所关注的用户的所有图片,我不知道要添加什么更改以返回我的图像(我的user_id = 3)。所有用户名必须是用户名(不是id),用户名在“用户”表中

 $sql = "SELECT u.username, p.image, p.date
    FROM users u, user_follow f, images p
    WHERE f.user_id = 3 AND f.follow_id = u.id AND f.follow_id = p.user_id
    ORDER BY p.date DESC";

它返回:

[0] => Array
    (
        [id] => 8
        [image] => fsfsf
        [date] => 2012-01-24 14:58:14
    )

[1] => Array
    (
        [id] => 7
        [image] => first.jpg
        [date] => 2012-01-24 14:42:27
    )

[2] => Array
    (
        [id] => 7
        [image] => second.jpg
        [date] => 2012-01-24 14:42:27
    )

[3] => Array
    (
        [id] => 6
        [image] => the_last.jpg
        [date] => 2012-01-24 01:49:45
    )

我关注的用户及其图片,但没有来自user_id的图片

2 个答案:

答案 0 :(得分:2)

SELECT
   images.*,
   users.username
FROM images
LEFT JOIN users ON images.user_id = users.id
LEFT JOIN user_follow ON images.user_id = user_follow.follow_id
WHERE images.user_id = 3 OR user_follow.user_id = 3
ORDER BY images.date DESC

答案 1 :(得分:1)

SELECT image
FROM images
WHERE user_id = 3
OR user_id IN (
    SELECT follow_id
    FROM user_follow
    WHERE user_id = 3
)
ORDER BY date DESC;