2013-01-13 2 views
0

빠른 모든 질문에 대한 질문이 있습니다.XML 여러 하위 섹션

여러 데이터가있는 하위 섹션이있는 XML 형식의 테이블에서 데이터를 가져 오려고합니다. 직원이있는 관리자 목록입니다. 조직도처럼 생각하십시오. 그것은이 모든과 같은 하나 개의 테이블에서오고있다 :

<manager> 
    <id>0049</id> 
    <name>John Doe</name> 
    <employees> 
    <employee> 
     <id>4433</id> 
    </employee> 
    <employee> 
     <id>4430</id> 
    </employee> 
    </employees> 
</manager> 

내가 여기에서 발견 된 일부 간단한 쿼리를 작성 시도했다 :

| ManagerID| EmployeeID | 
|  0049 | 4433 | 
|  0049 | 4430 | 

나는이 필요합니다. 그러나 숫자가 많을 수 있기 때문에 제대로 작동하지 않습니다. 동일한 관리자에 대해 여러 레코드를 얻고 있습니다.

관리자 당 1 명만 필요합니다. 적절한 쿼리가 무엇입니까?

+0

관리자 이름은 어디에서 왔습니까? 두 가지 레벨 이상인 경우 XML 결과는 어떻게됩니까? 어떤 DBMS가 이것을위한 것인가? –

답변

0

저는 계층 적 SQL 쿼리를 좋아하지 않습니다. 그렇습니다. 많은 SQL 데이터베이스에서 지원되지만, 메모리 포스트 프로세싱은 정말 간단하고 직선적이며, 더 중요한 것은 쉽게 개선하고 데이터의 버그를 수정하십시오.

대략 다음과 같은 예가 PHP 입니다. 동일한 Manager-> Employee 관계를 읽고 전체 계층 구조를 JSON 객체로 내 보냅니다.

최종 개체를 JSON 대신 XML로 serialize해야합니다.

// Connect to your Database 
mysql_connect("localhost", "username", "password") or die(mysql_error()); 
mysql_select_db("test") or die(mysql_error()); 

// Select accounts 
$response = mysql_query("SELECT EmployeeID as id, ManagerID as parentid, name, title, description, phone, email, photo FROM accounts") or die(mysql_error()); 

// create some class for your records 
class Account 
{ 
    public $id = 0; 
    public $parentid = null; 
    public $name = ''; 
    public $title = ''; 
    public $desciption = ''; 
    public $phone = ''; 
    public $email = ''; 
    public $photo = ''; 

    public $children = array(); 

    public function load($record) { 
     $this->id = intval($record['record_id']); 
     $this->parentid = intval($record['parentid']); 
     $this->title = $record['title']; 
     $this->name = $record['name']; 
     $this->description = $record['description']; 
     $this->phone = $record['phone']; 
     $this->email = $record['email']; 
     $this->photo = $record['photo']; 
    } 
} 

// create hash and group all children by parentid 
$children = Array(); 
while($record = mysql_fetch_array($response)) 
{ 
    $account = new Account(); 
    $account->load($record); 

    if(!isset($children[$account->parentid])) { 
     $children[$account->parentid] = array(); 
    } 
    array_push($children[$account->parentid], $account); 
} 

// Create hierarchical structure starting from $rootAccount 
function recursiveLoadChildren($parent, $children) { 
    if(isset($children[$parent->id])) { 
     foreach($children[$parent->id] as $id => $account) { 
      array_push($parent->children, $account); 
      recursiveLoadChildren($account, $children); 
     } 
    } 
} 

$rootAccount = $children[0][0]; 
recursiveLoadChildren($rootAccount, $children);  

// serialize $rootAccount object including all its children into JSON string 
$jsonstring = json_encode($rootAccount);