快速提问所有大师们。
我正在尝试以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个。什么是正确的查询?
答案 0 :(得分:0)
我不喜欢分层SQL查询,是的,许多SQL数据库都支持它们,但我喜欢内存后处理,因为它非常简单直接,更重要的是,你可以轻松地改进和修复数据中的错误。
以下是您必须做的事情,以下示例在PHP中 它读取相同的Manager-&gt; 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);