编写具有多个连接的MySQL语句

时间:2011-12-22 18:21:22

标签: mysql

我有4张桌子,它们是:

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

我甚至不确定我的表是否设置正确以便检索此信息。任何让我越过驼峰的帮助将不胜感激。

1 个答案:

答案 0 :(得分: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