我有一个查询
select c.CommentId
,c.CommentText
, c.CommenterId
, c.CommentDate
, u.first_name
, u.last_name
, i.ImageName
, i.Format
from comment c
join users u
on c.CommenterId = u.user_id
join user_profile_image i
on u.user_id = i.UserId
where PostId = 76
order
by CommentDate desc
limit 10
当表中的i.ImageName字段为空时,此查询返回空结果。如果ImageName字段是emty,我想返回该行。我该怎么做?
答案 0 :(得分:2)
JOIN
默认为INNER JOIN
- 尝试更改
join user_profile_image i
到
LEFT join user_profile_image i
这里接受的答案有一个很好的视觉解释:Difference in MySQL JOIN vs LEFT JOIN
答案 1 :(得分:2)
要在ImageName字段为空时包含行,请使用LEFT JOIN
,如下所示:
SELECT c.CommentId,c.CommentText, c.CommenterId, c.CommentDate, u.first_name,
u.last_name,i.ImageName,i.Format
FROM comment c
INNER JOIN users u ON c.CommenterId=u.user_id
LEFT JOIN user_profile_image i ON u.user_id=i.UserId
WHERE PostId = 76
ORDER BY CommentDate DESC
LIMIT 10;
答案 2 :(得分:2)
问题不完全是i.ImageName
为空。问题是没有与用户关联的图像。 <{1}}找不到图像,没有匹配,则不返回用户。
解决方案是使用join
。我倾向于使用left join
完全编写查询:
left join
注意:这假设select c.CommentId, c.CommentText, c.CommenterId, c.CommentDate,
u.first_name, u.last_name,
i.ImageName, i.Format
from comment c left join
users u
on c.CommenterId = u.user_id left join
user_profile_image i
on u.user_id = i.UserId
where PostId = 76
order by c.CommentDate desc
limit 10;
位于PostId
表中,根据表名称这似乎是合理的。