2015-11-21 146 views
0

我有一個查詢SQL查詢行爲奇怪

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.I​​mageName場是表空。如果ImageName字段是emty,我想返回該行。我應該怎麼做?

+3

使用左外連接 – andrew

+1

出於好奇,爲什麼你會在一個表中調用一個字段'user_id',而在另一個表中調用'userid'? –

+1

@GordonLinoff你是什麼意思?我用一些現成的登錄系統,使用下劃線,但我個人不喜歡這個..如果這回答你的好奇心? – whatever

回答

2

JOIN默認爲INNER JOIN爲MySQL - 嘗試改變

join user_profile_image i

LEFT join user_profile_image i

這裏接受的答案具有良好的視覺解釋:Difference in MySQL JOIN vs LEFT JOIN

+0

現在我要麼太累了,要麼我很愚蠢......我不知道該怎麼辦......嗯謝謝.. – whatever

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; 
+0

謝謝!!!!!! !!!!!!!!!!!!!!! – whatever

2

的問題是不完全是i.ImageName。問題是沒有與用戶關聯的圖像。 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; 

注:這是假設PostIdcomment表,這似乎是合理的給出的表名。

+0

謝謝!!!!!!!!!!!!!!!!!!! 1 – whatever