如何起诉子查询

时间:2011-09-01 09:59:13

标签: mysql subquery

  $logged = $_SESSION['logged'];

  $construct =  "SELECT child.* 
                 FROM products child 
                 LEFT JOIN products parent on parent.sid=child.sid 
                 WHERE parent.id =
                   '(SELECT productid 
                     FROM subscribed 
                     WHERE username=\"$logged\")' 
                 AND parent.keyword != child.name 
                 ORDER BY child.id DESC";  

我无法让子查询工作,我得到了错误的结果。父查询很好,因为我之前使用过它。

我希望子查询从表'subscribed'获取所有产品,其中username = $ logged。

这是我想要的,但在一个查询中,检查WHERE子句的差异。

$construct =  "SELECT child.* 
               FROM products child 
               LEFT JOIN products parent on parent.sid=child.sid 
               WHERE parent.id= 
                 'SUB QUERY RESULT 1' 
               AND parent.keyword != child.name 
               ORDER BY child.id DESC"; 

$construct =  "SELECT child.* 
               FROM products child 
               LEFT JOIN products parent on parent.sid=child.sid 
               WHERE parent.id=
                 'SUB QUERY RESULT 2' 
               AND parent.keyword != child.name 
               ORDER BY child.id DESC"; 

$construct =  "SELECT child.* 
               FROM products child 
               LEFT JOIN products parent on parent.sid=child.sid 
               WHERE parent.id=
                 'SUB QUERY RESULT 3' 
               AND parent.keyword != child.name 
               ORDER BY child.id DESC"; 

如何在不循环查询的情况下在一个查询中执行此操作。我甚至需要子查询吗?

1 个答案:

答案 0 :(得分:1)

您可以使用内部联接来执行您想要的操作:

 $construct = "SELECT child.*         
   FROM products child         
   LEFT JOIN products parent on parent.sid=child.sid         
   INNER JOIN subscibed s ON (s.productid = parent.id) 
   WHERE s.username = '$logged' 
     AND parent.keyword != child.name         
   ORDER BY child.id DESC";  

如果您希望三个查询加入一个:

$construct =  "SELECT child.*              
           FROM products child              
               LEFT JOIN products parent on (parent.sid = child.sid)              
           WHERE parent.id IN             
                 (SELECT productid FROM table1 WHERE username= '$logged'
                UNION 
                  SELECT productid FROM table2 WHERE something = '$somethingelse'
                UNION 
                  SELECT productid FROM table3 WHERE otherthing = '$otherstuff'
                 )              
           AND parent.keyword != child.name              
           ORDER BY child.id DESC";