2011-04-25 38 views
0

我有一個關於從多個表建立一個mysql查詢的問題。 這些表如下:有人可以幫我用mysql查詢嗎?

comments: comment_id, entry_id, user_id, comment, time.. 
users: user_id, user_name.. 
profile_photos: photo_id, user_id, photo_name 

我想從意見表中的所有comments特定entry_id,併爲所有這些用戶(誰寫的評論),我想要得到的photo_id(從profile_photos表,和用戶表中的user_name)。

例如2個用戶user_id「1」和「2」對「entry_id」「1」發表了評論。我想從這兩個用戶的評論表中獲取評論數據,以及他們的user_name和photo_id。

如果有人能幫助我查詢,我會非常感激。

+2

第一個停靠港:http://en.wikipedia.org/wiki/Join_(SQL) – YXD 2011-04-25 20:41:59

回答

1
SELECT 
     c.comment_id, 
     c.user_id, 
     c.comment, 
     c.time, 
     u.user_name, 
     p.photo_name 
    from 
     comments c 
     join users u 
      on c.user_id = u.user_id 
     left join profile_photos p 
      on u.user_id = p.user_id 
    where 
    c.entry_id = WhateverNumberYouWant 

添加上任何其他列從各自的別名表(「C」 =評論,「U」 =用戶,「P」 =照片)

左聯接是以防萬一沒有照片但對於給定的用戶...它不會排除這樣的用戶的任何條目。

1
SELECT comment, user_name, photo_name 
FROM comments 
JOIN users ON (comments.user_id = users.user_id) 
JOIN profile_photos ON (users.user_id = profile_photos.user_id) 
WHERE entry_id = {entry_id} 
1

嘗試以下方法,其中entry_id是XXX,我包括USER_NAME太

select comments.comment,profile_photos.photo_id,users.user_name 
from comments,users,profile_photos 
where 
    comments.entry_id = xxx and 
    users.user_id = comments.user_id and 
    users.user_id = profile_photos.user_id; 
相關問題