结合JOIN和获得"孩子"行

时间:2017-05-15 12:55:24

标签: mysql sql

为了使问题更简单,我们假设我们有两个包含少量列和一对多关系的表...

  1. first包含字段idsome_fieldsecond_id
  2. second包含字段idparent_id
  3. 首先我做

    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.idfirst.some_fieldsecond.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>) 
    

1 个答案:

答案 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")