简体   繁体   中英

mysql query select depending on 2 tabels

I've reached the php code that I want. But my website is too slow because it keeps repeating and round over and over again,

$pages= mysql_query("SELECT * FROM ex_instagram_p WHERE type = '".follow."' AND active=1 And username !='".$username."' ORDER BY cpc DESC" );
$prow = mysql_fetch_array($pages);



Do{
$dollowed = mysql_query("SELECT * FROM exchanges WHERE user = '".$username."' AND exid = '".$prow['id']."'");

$followed = mysql_num_rows($dollowed);
;}while($followed > 0 && $prow = mysql_fetch_array($pages));

Actually I can explain the code a little more, I need to choose the maximum CPC row from the first table But also to make sure that:

type = '".follow."' AND active=1 And username !='".$username."' ORDER BY cpc DESC"

And here comes the problem, before continue I need to make sure that the 'id' field form the first table does't got a record on the second table with the user username,

is it got result it'll repeat again using the next row, over and over until finding a result that satisfies both tables. This method is soooo heavy

I hope to get a simpler and lighter way, thanks

I've tried to do this but it does not work

$prow= mysql_query("SELECT *
 FROM (mysql_query("SELECT * FROM ex_instagram_p WHERE type = '".follow."' AND active=1         
And username !='".$username."' ORDER BY cpc DESC" );)
INNER JOIN (mysql_query("SELECT * FROM exchanges WHERE user = '".$username."'");)
ON ex_instagram_p.id=exchanges.exid";); 

You can do this in one query. It is a bit hard to follow the logic, but I think this is the query that you want:

SELECT i.*
FROM ex_instagram_p i join
     exchanges e
     on i.id = e.exid
WHERE i.type = '".follow."' AND i.active=1 And
      i.username <> '".$username."' and e.user = '".$username."'
ORDER BY i.cpc DESC
LIMIT 1;

Doing the work in the database is generally much faster than cycling through rows in the application. After all, that is what databases are good for -- managing and querying large amounts of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM