为了使问题更简单,我们假设我们有两个包含少量列和一对多关系的表...
first
包含字段id
,some_field
和second_id
。second
包含字段id
,parent_id
首先我做
SELECT first.id, first.some_field, second.id, second.parent_id
FROM first INNER JOIN second ON first.second_id = second.id
WHERE some_field="some_val"
但之后我需要从两个表的连接中获取first.id
,first.some_field
,second.id
,其中parent_id
位于上述查询的相应结果列中的值中
这可以通过一个查询完成吗?或者(在PHP方面)我需要在结果集中取列,并执行以下操作?
SELECT first.id, first.some_field, second.id, second.parent_id
FROM first INNER JOIN second ON first.second_id = second.id
WHERE parent_id IN (<many_ids_here>)
答案 0 :(得分:1)
您可以创建嵌套查询,如下所示:
SELECT first.id, first.some_field, second.id, second.parent_id
FROM first INNER JOIN second ON first.second_id = second.id
WHERE parent_id IN (SELECT DISTINCT second.parent_id FROM first INNER JOIN second ON first.second_id = second.id WHERE some_field="some_val")