2011-09-16 12 views
0

私は、データベースからいくつかのデータを呼び出すことに問題がある...SQLとPHPの問題は - のみ最初のカテゴリ

私は各productonly 1つのIDのためにぐるぐる通常のデータを持っていますが、私はその製品のカテゴリテーブルを持っています製品がより多くのカテゴリに含まれる可能性があるため、同じIDを2回以上持つこと。データを呼び出すクエリがありますが、カテゴリテーブルの最初のカテゴリのみを選択する方法はわかりません。例えば

、テーブル:

product_id | category_id 
2    | 31 
2    | 12 
2    | 31 
3    | 14 
3    | 38 
4    | 10 

私は他のデータを呼び出すために使用このクエリ:

SELECT toc_products.products_id, 
     toc_products_description.products_name, 
     toc_products.manufacturers_id, 
     toc_products.products_price, 
     toc_products_description.products_url, 
     toc_manufacturers.manufacturers_id, 
     toc_manufacturers.manufacturers_name 
FROM toc_products, 
     toc_products_description, 
     toc_manufacturers 
WHERE toc_products.products_id = toc_products_description.products_id 
     AND toc_products.manufacturers_id = toc_manufacturers.manufacturers_id 
     AND toc_products_description.language_id = 14 
ORDER BY toc_products.products_id 

ので、私は今のところ、私はこれだけを持って、しばらく呼び出すためにこのすべてを必要とします:

次のIDと同じIDを持つ場合は、IDを持つ最初の値のみをクエリで呼び出す方法はありますかt ??私の英語のための

助けてください、と申し訳ありません...おかげ

+0

あなたのコードにcategory_idのようなものはありません。 – roselan

答えて

-1

はちょうどあなたの声明

SELECT toc_products.products_id, 
     toc_products_description.products_name, 
     toc_products.manufacturers_id, 
     toc_products.products_price, 
     toc_products_description.products_url, 
     toc_manufacturers.manufacturers_id, 
     toc_manufacturers.manufacturers_name 
FROM toc_products, 
     toc_products_description, 
     toc_manufacturers 
WHERE toc_products.products_id = toc_products_description.products_id 
     AND toc_products.manufacturers_id = toc_manufacturers.manufacturers_id 
     AND toc_products_description.language_id = 14 
ORDER BY toc_products.products_id 
GROUP BY category_id 
+0

他の戻り値をaggreagtingせずにフィールドでグループ化することはできません(max()またはsum()) – roselan

0

あなたは基本的に3つのオプションを持っているの底にGROUP BY category_idを追加します。

最初にSQLでカテゴリIDを選択し、の順番にを入力します。実際には、1)製品と2)カテゴリによるご注文。その後、PHPが変更されているかどうかチェックすることができます。

$oldCategory = null; 
while($red = mysql_fetch_array($rezultat)) 
{ 
    if ($oldCategory != $red['category']) 
    { 
    if ($red['products_quantity'] = 0) $red['products_quantity'] = 'Nicht lagernd'; 
    else $red['products_quantity'] = 'Lagernd'; 

    echo $red['products_id'], ", ", $red['products_name'], ", ", $red['products_price'], ", ", $red['manufacturers_name'], ", ", $red['products_url']; 
    echo "<br />"; 
    } 
    $oldCategory = $red['category']; 
} 

秒:あなたは、SQLを変更しないと、各製品のために、データベースからカテゴリを取得するPHPの関数を作成することができます。

3番目:純粋なSQLで行います。がんばろう。

関連する問題