在数据库中有两个表:
secondNames:
id | name
--------------
1 | John
2 | Peter
3 | Michael
名:
id | name | secondNames_id
----------------------------
1 | Jack | 2
2 | Harry | 2
3 | James | 1
假设我有来自secondName表的名称,并且想要选择具有该第二名称的人的姓名。作为SQL的初学者我喜欢这样:
SELECT id FROM secondNames WHERE name = 'some name';
SELECT name FROM names WHERE secondNames_id = 'id from first select';
是否可以在一个查询中执行此操作以及如何执行此操作?
答案 0 :(得分: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 :(得分:1)
您可以使用scalar subquery:
SELECT name
FROM names
WHERE secondNames_id = (SELECT id
FROM secondNames
WHERE name = 'some name');