2011-01-06 4 views
0

나는 user_id에 의한 모든 요청을 수집하고 검색된 레코드와 연관된 profile_id에서 프로파일 이름을 가져 오는이 쿼리를 가지고있다.여러 개의 기본 키를 공유하는 3 개의 테이블에서 mysql 쿼리를 수행 할 수 있습니까?

SELECT Requests.request_id,Requests.user_id,Requests.profile_id,Requests.job_title,Requests.date,Requests.time,Requests.info,Requests.approval, Profile.first_name, Profile.last_name FROM Requests, Profile WHERE user_id = '$user_id' AND Requests.profile_id = Profile.profile_id ORDER BY approval ASC 

계정 테이블에서 user_id의 이름을 검색하기 위해 다른 테이블을 추가하려면 어떻게해야합니까?

답변

1

더 명쾌하기 때문에 조인을 사용하는 것이 좋은 아이디어라고 생각합니다.

SELECT Requests.request_id,Requests.user_id,Requests.profile_id,Requests.job_title,Requests.date,Requests.time,Requests.info,Requests.approval, Profile.first_name, Profile.last_name, OtherTable.other_field FROM Requests 
LEFT JOIN Profile ON Requests.profile_id = Profile.profile_id 
LEFT JOIN OtherTable ON Requests.profile_id = OtherTable.profile_id 
WHERE Request.user_id = '$user_id' ORDER BY approval AS 
0

user_id가 일부 사용자 테이블의 기본 키이고이 레코드가 해당 사용자에게 속한다는 것을 나타내는 user_id 참조가있는 테이블이 필요합니다.

MySQL JOIN을 사용하십시오. 예를 들어, 사용자가 테이블에 가입하는 것이 좋습니다. user.user_id = groups.user_id

0

이와 비슷한?

select 
    r.request_id 
    , r.user_id 
    , r.profile_id 
    , r.job_title 
    , r.date 
    , r.time 
    , r.info 
    , r.approval 
    , p.first_name 
    , p.last_name 
    , a.something 
from Requests as r 
join Profile as p on p.profile_id = r.profile_id 
join Accounts as a on a.user_id = r.user_id 
where user_id = '$user_id' 
order by r.approval asc ; 
관련 문제