2016-12-02 70 views
1

在数据库中有两个表:是否可以在一个SQL查询中选择它?

secondNames:

id | name  
-------------- 
1 | John  
2 | Peter 
3 | Michael 

名称:

id | name | secondNames_id 
---------------------------- 
1 | Jack |  2   
2 | Harry |  2   
3 | James |  1   

说我从secondName表有名字和要选择的人的名字谁拥有第二名称。作为一个在SQL上begginer我这样做:

SELECT id FROM secondNames WHERE name = 'some name'; 
SELECT name FROM names WHERE secondNames_id = 'id from first select'; 

是否有可能在一个查询中做到这一点,以及如何?

+0

由'ID = secondNames_id'加入名称表 –

回答

3

这应该工作:

Select n.name 
from secondNames as sn 
inner join names as n on n.secondNames_ID = sn.id 
where sn.name = 'some name' 
1

您可以只使用一个scalar subquery

SELECT name 
FROM names 
WHERE secondNames_id = (SELECT id 
         FROM secondNames 
         WHERE name = 'some name'); 
相关问题