使用多个连接编写MySQL语句
我有4张桌子,它们是:使用多个连接编写MySQL语句,mysql,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: i
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
我甚至不确定我的表是否正确设置以检索此信息。如果能帮我渡过难关,我将不胜感激 试试这个,我想这正是你想要的
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
就这样!非常感谢你!很高兴它对你有用,关于清晰数据库结构的问题+1