Jump to content

Combine 2 MySql Queries


transfield

Recommended Posts

Hi,

I am currently using the results of one query to query another table. I'm looking for a simple solution to combine both these queries into a single query & achieve the same result. Part of my code is below. Could you please help me to re-write my query? Thanks.

$query1=("SELECT * FROM test_log WHERE '$mktime' < expiry ORDER BY id DESC"); 
    $result1=mysql_query($query1); 
    $num1=mysql_num_rows($result1);


while ($row1 = mysql_fetch_array($result1))
    { 
    $id = $row1["id"];
    $keyword = $row1["keyword"];
    $sale = $row1["sale_rent"];
    $agents = $row1["e_num"];
    $email = $row1["email"];
    $cc_email = $row1["cc_email"];
    $expiry = $row1["expiry"];
    
    $query2= ("SELECT * FROM condo WHERE (location LIKE '%{$row1['keyword']}%' AND sale_rent LIKE '%{$row1['sale_rent']}%' AND e_num LIKE '{$row1['e_num']}') AND (date >= '$sendate') AND TRIM(IFNULL(`phone_1`,'')) <> '' ORDER BY sale_rent, location");
    $result2=mysql_query($query2);    
$num2=mysql_num_rows($result2);

From the code above, I am using the results of $query1 to query the condo table ($query2). So now I want to do away with two queries & have just one query to achieve the same results.

 

Could you show me the code please?

 

Thanks

Edited by transfield
Link to comment
Share on other sites

When you are selecting information from multiple tables you use a JOIN command.  This is part of the core functionality of a relational database - you build relations between the tables of data. You really should take the time to learn about this.

 

Looking at your queries there seems to be some fundamental flaws in your table design.  can you post up describe's of your tables and detail any fields that relate across tables?

Link to comment
Share on other sites

Give this a try

 

SELECT c.*
 
FROM condo c
JOIN test_log tl
   ON c.location LIKE tl.keyword
  AND c.sale_rent LIKE tl.sale_rent
  AND c.e_num LIKE tl.e_num
 
WHERE (c.date >= '$sendate')
  AND TRIM(IFNULL(c.phone_1,'')) <> ''
 
ORDER BY c.sale_rent, c.location
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.