-1

对所有大师的快速提问。

我正在尝试以 XML 格式从表中提取数据,该表具有包含多个数据的子部分。这是一个经理及其员工的列表。想像一个组织结构图。这一切都来自一个看起来像这样的表:

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

我需要这个:

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

我试过写一些我在这里找到的简单查询。但是,由于数量可能很高,因此无法正常工作。我正在为同一个经理获取多条记录。

我只需要每个经理 1 个。什么是正确的查询?

4

1 回答 1

0

我不喜欢分层 SQL 查询,是的,许多 SQL 数据库都支持它们,但我喜欢内存后处理,因为它非常简单直接,更重要的是,您可以轻松改进和修复您的错误数据。

这是您大致要做的事情,以下示例在 PHP 中读取相同的 Manager->Employee 关系并将整个层次结构导出为 JSON 对象。

在您的情况下,您必须将最终对象序列化为 XML 而不是 JSON。

// 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);
于 2013-01-16T03:23:43.130 回答