2012-03-22 33 views
1

我有一個嵌套的查詢,當我在SQL Server 2008管理工作室中執行時,它完美地工作,它輸出兩個結果,但是當我嘗試在PHP中執行此操作時我收到一個錯誤,我認爲這與PHP輸出有關。使用SQL服務器和PHP做嵌套SQL查詢的正確方法

因此,這裏是其中的工作原理SQL服務器的查詢,但我認爲這是不正確的:

select * from product_catalogue where catalogueid =(select catalogueid from products where productid = 1) (select * from products where productid = 1) 

這裏是PHP完整的查詢:

 $query3 = "select * from product_catalogue where catalogueid =(select catalogueid from products where productid = '" . $productid . "') (select * from products where productid = '" . $productid . "')";      

    $result3 = sqlsrv_query($conn, $query3, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET)); 

    if($result3 === false) 
    { 
     echo "Error in query preparation/execution.\n"; 
     die(print_r(sqlsrv_errors(), true)); 
    } 


     while($obj = sqlsrv_fetch_object($result3)) 
        { 

         $prod_image = $obj->picturem; 
         $prod_id = $obj->catalogueID; 
         $prod_description = $obj->description; 
         $prod_price = $obj->product_price; 
         echo "<p>$prod_id" ; 
         echo "<br/>$prod_description" ; 
         echo "<br/>&pound;$prod_price"; 
         echo "<br/><br/><img src='$prod_image' width='200' height='400'/>"; 
         echo "<br/><br/>"; 
         } 

錯誤我收到當運行這個查詢是這樣的:

Error in query preparation/execution. Array ([0] => Array ([0] => 01000 [SQLSTATE] => 01000 [1] => 16954 [code] => 16954 [2] => [Microsoft][SQL Server Native Client 10.0][SQL Server]Executing SQL directly; no cursor. [message] => [Microsoft][SQL Server Native Client 10.0][SQL Server]Executing SQL directly; no cursor.) [1] => Array ([0] => 01S02 [SQLSTATE] => 01S02 [1] => 0 [code] => 0 [2] => [Microsoft][SQL Server Native Client 10.0]Cursor type changed [message] => [Microsoft][SQL Server Native Client 10.0]Cursor type changed)) 

我一直在研究嵌套查詢以及尋找通過PHP手冊試圖瞭解更多關於如何輸出結果的信息,我只是覺得它是因爲它在SQL Server管理工作室中有效,並不意味着語法是正確的。任何建議表示讚賞。

回答

4

其實,這是兩個完全獨立的查詢:

select * from product_catalogue where catalogueid =(select catalogueid from products where productid = 1) 

(select * from products where productid = 1) 

做你想做的最簡單的方法是加入在單個查詢表 - 是這樣的:

select c.catalogueID, 
     c.product_name, 
     c.product_price, 
     c.description, 
     p.productID, 
     p.picturem, 
     p.picturew 
from product p 
join product_catalogue c on c.catalogueid = p.catalogueid 
where p.productid = 1 
+0

是的我覺得這是問題所在,我實際上正在做兩個查詢,期待PHP將它作爲一個整體來處理它。前段時間我被告知我不記得在哪裏或什麼時候,但如果它在SQL管理工作室中起作用,它應該在其他地方工作。我會嘗試使用JOIN,謝謝。 – deucalion0 2012-03-22 09:26:31

+0

我一直在研究連接,但無法弄清楚如何正確地做到這一點,因爲我想從兩個表中選擇全部,這可能嗎? 謝謝! – deucalion0 2012-03-22 10:35:19

+0

@ deucalion0:你能列出你想從每個表中返回的列嗎?我問的原因是,不同的表具有相同的列名稱,SQL查詢通常需要不同的列別名(否則它們將返回錯誤)。另外,最好只選擇所需的列,而不是所有查詢表上的所有列。 – 2012-03-22 10:39:58