【问题标题】:Get data from three table SQL从三表SQL获取数据
【发布时间】:2012-01-24 19:44:59
【问题描述】:

我的 MySQL 表结构(3 个表)

用户

身份证
用户名

图片

身份证
用户ID
图片

user_follow

身份证
用户ID
follow_id

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

现在查询,它给了我关注的用户的所有图片,我不知道要添加哪些更改以返回我的图片(我的 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 中没有我的图像

【问题讨论】:

  • 如果您试图获取“'images' 表中的所有图像”,那么用户名变量在哪里发挥作用?
  • 我正确理解你在这里 f.follow_id = u.id。我的用户在 users 表中有 id,但其他用户在 user_id 字段中有相同的 id

标签: php mysql sql


【解决方案1】:
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

【讨论】:

  • 接受最佳答案有助于提高接受率。如果它已经太低,用户将停止帮助您。
【解决方案2】:
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;

【讨论】:

    猜你喜欢
    • 2017-07-08
    • 2020-09-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2010-09-13
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多