4

ループ内でdbクエリを決して使用しないことを学んだ私の別の質問から来て、ループする前に便利な方法ですべてのデータを取得する方法を学ばなければなりません。

「スケール」と「アイテム」の 2 つのテーブルがあるとします。items 内の各アイテムは、scale 内の 1 つの scale に属し、外部キー (scaleID) でリンクされます。最初の次元がすべての列を含むすべてのスケールであり、1 つのスケールのすべての列のすべての項目がネストされるように、1 つのクエリですべてのデータを配列構造にフェッチしたいと考えています。

結果は次のようになります。

scale 1, scaleParam1, scaleParam2, ...
....item1, itemParam1, itemParam2, ...
....item2, itemParam1, itemParam2, ...
scale 2, scaleParam2, scaleParam2, ...
....item1, itemParam1, itemParam2, ...
....item2, itemParam1, itemParam2, ...

これまでのところ、主に 1 対 1 の関係の左結合を行ってきました。これは一対多であり、私はそれについて頭を悩ませることはできません。

それは正しい結合ですか、サブクエリでも実行できますか、外側の行全体を取得する方法も...

後で、ネストされた foreach ループを使用して反復処理したいと思います。

頭が悪いだけなのかな…

4

2 に答える 2

6

The query should look something like this:

SELECT * FROM scales
INNER JOIN items ON scales.id = items.scale_id

If you want to iterate through with nested loops, you'll need to pull this data into an array - hopefully you're not pulling back so much that it'll eat up too much memory.

$scales = array();

while ($row = mysql_fetch_assoc($data))
{
    if (!isset($scales[$row['scale_id']]))
    {
        $row['items'] = array();
        $scales[$row['scale_id']] = $row;
    }

    $scales[$row['scale_id']]['items'][] = $row;
}

Then you can loop through:

foreach ($scales as $scale)
{
    foreach ($scale['items'] as $item)
        ; //... do stuff
}

Note: this is somewhat naive in that $scale and $item will both contain fields from BOTH tables... if that's a problem then you need to change the assignments in the loop above to pull out only the fields you want.

于 2008-12-10T19:23:32.117 に答える
1

It might be easier to first get all the scales, then all the items.

//first get scales
while ($row = fetchrowfunctionhere()) {
    $scale = $scales->createFromArray($row);
}

//then get items
$lastId = null;
while ($row = fetchrowfunctionhere()) {
    $scaleId = $row['scaleID'];
    if ($lastId != $scaleId) {
        $scale = $scales->getByScaleId($scaleId);
    }
    $item = $items->createFromArray($row);
    $scale->addItem($item);
    $lastId = $scaleId;
}

or everything in one sql

$lastId = null;
while ($row = fetchrowfunctionhere()) {
    $scaleData = array_slice($row, 0, 5, true);
    $itemData = array_slice($row, 5, 5, true);
    $scaleId = $scaleData['scaleID'];
    if ($lastId != $scaleId) {
        $scale = $scales->createFromArray($scaleData);
    }
    $item = $items->createFromArray($itemData);
    $scale->addItem($item);
    $lastId = $scaleId;
}

everything as one happy array

while ($row = fetchrowfunctionhere()) {
    $scaleData = array_slice($row, 0, 5, true);
    $itemData = array_slice($row, 5, 5, true);
    $scaleId = $scaleData['scaleID'];
    if (!isset($scales[$scaleId])) {
        $scales[$scaleId] = $scaleData;
    }
    $itemId = $itemData['itemID'];
    $scales[$scaleId]['items'][$itemId] = $itemData;
}
于 2008-12-10T19:19:45.587 に答える