2011-12-22 57 views
2

我有4个表,它们分别是:写有多个MySQL的语句连接

job, community, state, and region. 

其结构如下:

job: 
columns: 
    id 
    community_id 
relations: 
    community: local_key: community_id, foreign_key: id 

community: 
columns: 
    id 
    state_id 
relations: 
    state: local_key: state_id, foreign_key: id 

state: 
columns: 
    id 
    name 
    region_id 
relations: 
    region: local_key: region_id, foreign_key: id 

region: 
columns: 
    id 
    name 

现在,我需要一个查询,将:

get all the jobs with matching communities: i.e.: j.community_id = c.id 

then, from those matches, get all of the jobs in communities with a state region_id = "1" 

我做得很好,拉着状态,但我陷入了试图拉动该地区。我得到了这个:

SELECT j.id 
FROM job j 
INNER JOIN community c 
ON j.community_id = c.id 
WHERE c.state_id = 35 

我甚至不知道如果我的表设置正确,以检索此信息。任何帮助让我越过驼峰将不胜感激。

回答

2

试试这个,我认为这是你想要的。

SELECT 
    r.name AS regionname, 
    s.name AS statename 
FROM 
    job j 
LEFT JOIN 
    community c ON c.id = j.community_id 
LEFT JOIN 
    state s ON s.id = c.state_id 
LEFT JOIN 
    region r ON r.id = s.region_id 
WHERE 
    r.id = 1 
+0

就是这样!非常感谢! – Patrick 2011-12-22 18:38:06

+0

很高兴为你工作,在清晰的数据库结构的问题+1 – MrCode 2011-12-22 18:49:17