2012-03-22 92 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