我的MySQL表结构(3个表)
用户
id
username
图像
id
user_id
image
用户关注
id
user_id
follow_id
我尝试进行查询,该查询为我提供“images”表中我(user_id = 3)和我关注“user_follow”表的 friend 的所有图像
现在查询,它给了我我关注的用户的所有图片,我不知道要添加哪些更改才能返回我的图像(我的 user_id = 3)。所有用户名必须在用户名(不是id)中,用户名在“users”表中
$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
)
我关注的用户及其图像,但没有来 self 的 user_id 的图像
最佳答案
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
关于php - 从三表SQL中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993063/