2011-04-25 4 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 

나는 (누가 댓글을 쓰셨), 내가 profile_photos 테이블에서합니다 (photo_id을 얻으려면 특정 entry_id 댓글 테이블의 모든 comments를 얻으려면, 그 모든 사용자를위한, user 테이블의 user_name).

예를 들어 2 명의 사용자 user_id "1"및 "2"는 "entry_id" "1"에 대한 의견을 작성했습니다. 나는 그 두 사용자의 주석 테이블에서 주석 데이터를 얻고 싶습니다. user_name과 photo_id도 마찬가지입니다.

누군가가 쿼리를 도와 주면 정말 감사 할 것입니다. 각각의 별칭 테이블에서 어떤 다른 컬럼에

+2

먼저 포트를 포함 해보십시오 – YXD

답변

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"= 사진)가 왼쪽 가입

어떤 사진이없는 경우를 대비하다 주어진 사용자의 경우 해당 사용자가 모든 항목을 제외하지는 않습니다. http://en.wikipedia.org/wiki/Join_(SQL) :

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; 
관련 문제