2013-07-10 117 views
0

我有三個表:http://sqlfiddle.com/#!2/c7317庫MySQLi一個查詢而不是兩個(單while循環而不是while循環while循環)

我想每行的輸出:

ProductId = 1 
ProductCode = 1 
ProductRetailPrice = 1 
SubProductThumb = 1.jpg (the first subproducts thumb, where ProductId = 1) 

Sub Products of ProductId 1 
--------------------------- 
SubProductId = 1 
SubProductPieces = 10 

SubProductId = 4 
SubProductPieces = 40 

SubProductId = 7 
SubProductPieces = 70 

我得到這個代碼與MySQL工作:

$show_product_content = mysql_query(" 
     SELECT DISTINCT a.`ProductId`, a.`ProductCode`, a.`ProductRetailPrice`, a.`ProductPrice`, a.`ProductOffer`, a.`ProductTopSeler`, a.`ProductStrass`, a.`ProductStatus`, b.`SubProductThumb` 
     FROM `Products` as a, `SubProducts` as b 
     WHERE b.ProductId=a.ProductId 
     GROUP BY a.`ProductId` 
    "); 

    while($row = mysql_fetch_array($show_product_content)) 
    { 
     echo '<br />ProductId = '.$row['ProductId'].'<br />'; 
     echo 'ProductCode = '.$row['ProductCode'].'<br />'; 
     echo 'ProductRetailPrice = '.$row['ProductRetailPrice'].'<br />'; 
     echo 'SubProductThumb = '. $row['SubProductThumb'].'<br /><br />'; 

     $product_id = $row['ProductId']; 
     $show_sub_product_content = mysql_query(" 
      SELECT SubProductId, SubProductPieces, SubProductStatus, SubProductRingSize6, SubProductRingSize7, SubProductRingSize8, SubProductRingSize9, c1.ColorHex as Color1, c1.ColorName as ColorName1, c2.ColorHex as Color2, c2.ColorName as ColorName2 
      FROM SubProducts 
      INNER JOIN Colors c1 ON c1.ColorId=SubProducts.SubProductColor1 
      INNER JOIN Colors c2 ON c2.ColorId=SubProducts.SubProductColor2 
      WHERE ProductId='$product_id' 
     "); 

     echo 'Sub Products of ProductId '.$product_id.'<br />------------------------------------<br />'; 

     while($row = mysql_fetch_array($show_sub_product_content)) 
     { 
      echo 'SubProductId = '.$row['SubProductId'].'<br />'; 
      echo 'SubProductPieces = '.$row['SubProductPieces'].'<br /><br />'; 
     } 
    } 

但我想這樣做與準備聲明和單個查詢,這是可能的嗎?

+0

很有可能,在查詢中使用INNER JOIN將所有結果合併到一個查詢中,然後遍歷這些結果。 – Rob

+0

你能幫我嗎? – user2564276

回答

0

我認爲在這個特定情況下,左連接應該是有用的。 我正在做一些測試,我會讓你知道的。

+0

好的男人,謝謝 – user2564276

1

你的單個查詢如下,我結合你的兩個查詢。

SELECT a.`ProductId`, a.`ProductCode`, a.`ProductRetailPrice`, a.`ProductPrice`, a.`ProductOffer`, a.`ProductTopSeler`, a.`ProductStrass`, a.`ProductStatus`, b.`SubProductThumb`, b.SubProductId, b.SubProductPieces, b.SubProductStatus, b.SubProductRingSize6, b.SubProductRingSize7, b.SubProductRingSize8, b.SubProductRingSize9, c1.ColorHex as Color1, c1.ColorName as ColorName1, c2.ColorHex as Color2, c2.ColorName as ColorName2 
    FROM `Products` as a, `SubProducts` as b 
    LEFT JOIN Colors c1 ON c1.ColorId=b.SubProductColor1 
    LEFT JOIN Colors c2 ON c2.ColorId=b.SubProductColor2 
    WHERE b.ProductId=a.ProductId 
    GROUP BY a.`ProductId` 
+0

這隻回聲一個子產品,我想呼應所有具有prodictid 1等子產品 – user2564276

+0

再試一次,因爲我更新查詢 – DevZer0

+0

仍然是一樣的。 – user2564276