开发者

Mysql three queries combined into one

I have three queries:

$data1 = mysql_query("SELECT * 
                        FROM 'table1' 
                       WHERE post_status = 'publish' 
                         AND 'post_title' LIKE '$letter%' 
                    ORDER BY 'post_title' ASC") or die(mysql_error()); 

while($info1 = mysql_fetch_array( $data1 )){ 
  $id = $info1['ID']; 
  $data2 = mysql_query("SELECT * 
                          FROM 'table2' 
                         WHERE post_id='$id' 
                           AND key = 'the_key'")  or die(mysql_error());  

   while($info2 = mysql_fetch_array( $data2 )){
     $key = $info2['value'];
   } 

   if ($key == 'something') {
     echo "..."; 
     $data3 = mysql_query("SELECT * 
                             FROM 'table3' WHERE postnumber='$id'")
                or die(mysql_error());
       while($info3 = mysql_fetch_array( $data3 )){
         echo $info3['counter'];
       }
       echo "...";
    }
 }

I would开发者_运维百科 like to use one query as three takes sometime, the queries I have tried take even longer...

I have spent a long time trying to solve this; this is not a 'do it for me', but please help.


The biggest problem is that after iterating through the 2nd query you take the 'value' of the last row returned.

But you cant rely on the ordering of rows returned from a database - so your query is no-deterministic.


Join your three tables on id.

Yeah, I could show you examples, but, there are tons of SQL JOIN examples already written. If you've looked at one of those, and have a question, ask it. But on the chance you haven't looked, let me not take up my time re-writing what you can more quickly google. (I'm not trying to be a smart-ass, just trying to most efficiently use my time and yours.)

Should you use a left join? Or a equ-join? I don't know, I don't know your data. If you want to replicate the code you have now, you'd use a left join. An equ-join is however, probably want you actually want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜