0

しばらくこれを使って作業しています..頭が良くなりません..すっごく...ここで助けてください;-)それは非常に簡単だと確信しています..

テーブル:

CREATE TABLE IF NOT EXISTS `items` (
 `item_id` bigint(20) NOT NULL AUTO_INCREMENT,
 `item_parent_id` bigint(20) NOT NULL COMMENT 'itemid which this item belongs to',
 `item_name` varchar(255) NOT NULL,
 `item_serialnumber` varchar(255) NOT NULL,
 `item_model` varchar(255) NOT NULL,
  PRIMARY KEY (`item_id`),
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

item_id とそれが属する item_id の配列を作成しようとしています - item_parent_id を介して - 再帰的に -

親に子が見つかった場合でも、その子が他の親の親であるかどうかを確認します。

このようなもので試してみました:

function get_item($item_id, $menu)
{
$sql = "
SELECT
    items.*,
    customers.*
FROM
    assets
LEFT JOIN item_customer_rel USING(item_id)
LEFT JOIN customers USING(customer_id)
WHERE
    items.item_parent_id = '".$parent."'
ORDER BY
    items.item_name
";
$res = mysqli_query($db, $sql) or die("ERROR: SQL Select a2a ancestor", $sql, mysqli_error($db) , $_SESSION["u_id"]);
while ($items = mysqli_fetch_assoc($res))
    $menu = build_ancestor_array($parent, $menu);
}


function build_ancestor_array($parent, $menu)
{
GLOBAL $db;
$sql = "
SELECT
    items.*,
    customers.*
FROM
    items
LEFT JOIN item_customer_rel USING(item_id)
LEFT JOIN customers USING(customer_id)
WHERE
    items.item_parent_id = '".$parent."'
";
$res = mysqli_query($db, $sql) or cc("ERROR: SQL Select a2a ancestor", $sql, mysqli_error($db) , $_SESSION["u_id"], $this_document);
while ($items = mysqli_fetch_assoc($res))
{
    if ($ancestor_item_array[$parent] == $items["item_id"])
        $menu = build_ancestor_array($parent, $menu);
    $ancestor_item_array[$parent] = $items["item_id"];

    // Creates entry into items array with current menu item id ie. $menu['items'][1]
    $menu['items'][$items['item_id']] = $items;
    $menu['items'][$items['item_id']]["connection_type"] = 2;
    // Creates entry into connected_to array. connected_to array contains a list of all items with connected_to
    $menu['connected_to'][$items['item_parent_id']][] = $items['item_id'];
}
return $menu;
} // end build item array

「レベル」が 1 つ下がるだけです。

4

3 に答える 3

0

以下を参照してください。2 links最近、これらに対する回答を投稿しました。これは純粋に行われますSQL

リレーショナル innoDB を使用した再帰的 MySQL クエリ

MySQLですべての子行を見つける方法は?

于 2013-04-16T19:05:01.817 に答える
-1

純粋な SQL では動作しません。

ストアド プロシージャを確認する必要があります。作成しようとしている SQL は、すべての関係が最初のレベルの接続であるかのように表示されるため、1 レベルだけ「内側」に移動します。

例えば。親→息子→孫→グソン

parent.item_parent_id = null
son.item_parent_id = parent
grandson.item_parent_id = son
ggson.item_parent_id = grandson

頑固な孫でも下層のつながりなら、一次つながりとして登場します。

悲しいことに、純粋なSQLではできません..それが、私がNOSQLデータベースに行くようになった理由の1つです。

于 2013-04-16T19:01:24.097 に答える