使用SQL server和PHP执行嵌套SQL查询的正确方法


The correct way to do nested SQL queries using SQL server and PHP

我有一个嵌套查询,当我在SQL server 2008 management studio中执行时,它运行得很好,它输出两个结果,但当我尝试在PHP中执行此操作时,我收到了一个错误,我认为这与PHP输出有关。

这里是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 management studio中工作,并不意味着语法是正确的。欢迎提出任何建议。

这实际上是两个完全独立的查询:

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