我有以下 SQL 查询:
SELECT band.id bid, band.name, bandInfo.summary, bandImage.url bandImage,
user.username, user.online, userImage.url userImage
FROM bands AS band
INNER JOIN band_info AS bandInfo ON band.id = bandInfo.bid
LEFT JOIN band_images AS bandImage ON band.id = bandImage.bid
LEFT JOIN band_followers AS follower ON follower.bid = band.id
RIGHT JOIN users AS user ON user.id = follower.uid
INNER JOIN user_info AS userInfo ON userInfo.uid = user.id
LEFT JOIN user_images AS userImage ON user.id = userImage.uid
WHERE ((band.activated = 1) AND (user.activated = 1)) AND (bandInfo.language = 'fr')
ORDER BY band.name
'users' 表包含所有用户(一行 = 一个用户)
'user_info' 表包含有关用户的所有信息(一行 = 一个用户)
'user_images' 表包含有关用户的所有图像(一行 = 一个用户)
'bands' 表包含所有音乐乐队(一行 = 一个乐队)
'band_info' 表包含关于一个乐队的所有信息(由于语言的原因,一个乐队的多行)
'band_images' 表包含有关波段的所有图像(一行 = 一个波段)
'band_followers' 表包含用户和乐队之间的所有关系(一行 = 一个关系,所以有很多行包含相同的乐队 ID 但不包含相同的用户 ID)
即使乐队 ID 不在 band_followers 表中,我也想检索所有乐队及其信息(INNER JOIN)。当乐队 ID 位于 band_followers 表中时,我也想检索所有乐队,并且用户 ID 上的 INNER JOIN 与用户信息(INNER JOIN)即使他没有任何图像也是如此。
我的问题只是 JOIN 关键字。我真的不知道我是否必须使用 LEFT 或 RIGHT JOIN
谢谢!
更新答案:
SELECT band.id bid, band.name, bandInfo.summary, bandImage.url bandImage, user.username, user.online, userImage.url userImage
FROM bands AS band
INNER JOIN band_info AS bandInfo ON band.id = bandInfo.bid
LEFT JOIN band_images AS bandImage ON band.id = bandImage.bid
LEFT JOIN band_followers AS follower ON band.id = follower.bid
LEFT JOIN users AS user ON user.id = follower.uid AND user.activated = 1
LEFT JOIN user_info AS userInfo ON userInfo.uid = user.id
LEFT JOIN user_images AS userImage ON user.id = userImage.uid
WHERE (band.activated = 1) AND (bandInfo.language = 'fr')
ORDER BY band.name
谢谢大家
最佳答案
您应该在 users
和 user_info
之前使用 LEFT JOIN
,就像在 band_followers
之前一样。 LEFT JOIN
表示返回先前表的所有行,即使它们与您正在加入的表中的任何内容都不匹配。 RIGHT JOIN
表示返回您要加入的表的所有行。因此,如果您使用 RIGHT JOIN users
,您将获得所有用户,而不仅仅是关注乐队的用户。
您还应该将测试 user.activated = 1
放入 LEFT JOIN users
的 ON
子句中。否则,您将过滤掉所有没有粉丝的乐队,因为他们没有任何拥有 user.activated
的粉丝。
关于mysql - 左/右/内连接mysql语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30948030/