开发者

How to sue subqueries

  $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=\"$logge开发者_StackOverflow社区d\")' 
                 AND parent.keyword != child.name 
                 ORDER BY child.id DESC";  

I'm having trouble getting the subquery to work i get the wrong results. The parent query is fine because i have used it before.

I want the sub query to get all productids from the table 'subscribed' where username=$logged.

This is what i want but in one query, check WHERE clause for differences.

$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"; 

How do I do this in one query without looping the query. Do I even need a subquery?


You can use an inner join to do what you want:

 $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";  

If you want the three queries join in one do:

$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"; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜