2011-02-17 30 views
0

相交与条件三个表我有3个表如何使用MySQL的

1.usertb 

email  funcarea 

2.professiontb 

email  experience 

3.generalinfo 

email  location 

我想这三个表使用字段电子邮件有3个条件像
funarea = 2和经验相结合> = 3和位置 ='悉尼'

因为我是一个新手到SQL我渴望知道如何实现这一点。请专家帮忙。

回答

1
select a.email,funarea,experience,location from usertb a 
left join professiontb b 
on a.email = b.email 
left join generalinfo c 
on a.email = c.email 
where 
funarea = 2 and experience >=3 and location = 'Sydney' 
1

如果你在每个表的至少一个条目:

(生硬的和愚蠢的,但它的工作原理)

SELECT * 
FROM usertb, professiontb, generalinfo 
WHERE usertb.email=professiontb.email AND professiontb.email=generalinfo.email AND usertb.funcarea=2 AND professiontb.experience>=3 AND generalinfo.location='Sydney'; 

如果你没有在每个表中的一项,我建议是使用LEFT JOIN语句。

SELECT * FROM usertb WHERE usertb.funcarea=2 
LEFT JOIN professiontb ON(usertb.email=professiontb.email AND professiontb.experience>=3) 
LEFT JOIN generalinfo ON(usertb.email=generalinfo.email AND generalinfo.location='Sydney'); 

因为,您应该从usertb中获取所有行,即使其他表中存在一些缺失的行。

希望它会有所帮助。

Vincent