从PHP如何在SQL Server中有效地执行此搜索?

时间:2015-05-04 16:09:53

标签: php sql-server

我有一个类似于以下内容的数据库结构:

Table A: PersonId, GroupId
Table B: GroupId, ParentGroupId

鉴于PersonId,我想找到该人群的父组中所有人的ID。

首先,我通过加入ParentGroupId为给定的PersonId选择B。然后我执行一段时间循环,根据上一次搜索中返回的PersonIdA选择并记录GroupId,并通过从以下ParentGroupId获取下一个B来继续循环 $sql = 'SELECT ParentGroupID FROM A WHERE PersonId = ' . $id; $result = $db->query($sql); $row = $db->fetch_array($result); $parent_group = $row['ParentGroupId']; if(!is_null($parent_group)) { $parent_ids = array(); while($parent_group > 0) { //is there a way to do this where I retrieve all managers <= lvl 6 at once, so I don't have to loop in order to 'tier up'? $sql = 'SELECT ParentGroupID, PersonID FROM B INNER JOIN A on ParentGroupID = A.GroupID WHERE ParentGroupID = ' . $parent_group; $result = $db->query($sql); $row = $db->fetch_array($result); $parent_group = $row['ParentGroupID']; $parent_ids[] = $row['PersonID']; } }

这是一种有效的搜索方式,还是有一种选择不会以这种方式“冒泡”?

(这是实际场景的简化版本,更改架构不是一个选项)

    form#form
            input(type="number" name="bufferNum" placeholder="Number") 
            label 
                input(type="radio" name="bufferType" value="Miles") 
                span Miles
            label 
                input(type="radio" name="bufferType" value="Feet") 
                span Feet
            label 
                input(type="radio" name="bufferType" value="Kilometers") 
                span Kilometers
            label 
                input(type="radio" name="bufferType" value="Meters") 
                span Meters
            label 
               input(type="radio" name="bufferType" value="Degrees") 
               span Degrees
            input(type="file" id="file" name="bufferFile")
            input(type="button" value="Buff")

1 个答案:

答案 0 :(得分:1)

将两个查询合并为一个会更有效:

$sql = 'SELECT ParentGroupID, PersonID
  FROM B 
  INNER JOIN A on ParentGroupID = A.GroupID 
  WHERE  ParentGroupID IN (
    SELECT ParentGroupID FROM A WHERE ParentGroupID > 0
    AND PersonId = ' . $id .')' ;