Jump to content

Joined query with averages


colby07

Recommended Posts

hey guys,

I've been trying to figure a solution to this problem for quite some time now and just can't seem to figure it out.

 

I have a search form with a bunch of fields that are used to query a database.

the query is of the following format. It generates all the records in the database for the matching search criteria in a form with fields type of house, location, size:

 

$set = FALSE;

  $query  = "SELECT * FROM table_name";

 

  if (!empty($type))

  {

      $query .= " WHERE type= '$type'";

      $set = TRUE;

  }

  if (!empty($location))

  {

      $query .= ($set===TRUE ? " AND" : " WHERE") . " location= '$location";

      $set = TRUE;

  }

  if (!empty($size))

  {

      $query .= ($set===TRUE ? " AND" : " WHERE") . " size = '$size'";

  }

 

 

$results = mysql_query($query)

or die(mysql_error());

 

while ($row = mysql_fetch_array($results)) {

extract($row);

 

 

}

 

I have two other tables in the database.  1) users and 2) pricelink.

 

In the pricelink table there are three fields: userid, houseid, and price.

In another form I let users give a price that they would pay for the associated houseid.

 

I managed to get a table output for the search criteria above but I would like to join a field to the output table that would be the "average price" of all the suggested prices from the users (corresponding to the house ids of the search output records).

 

I tried a query based on results from the search of the user that looks like the following to get the right data I need:

 

$query2 = "SELECT houseid, AVG(price) FROM pricelink GROUP BY houseid";

 

but i need to limit the query to the searched house ids.

 

I think it isnt possible to add a WHERE houseid = "$houseid" clause in query2 but i need something of that nature.

 

I know this sounds confusing and I apologize in advance, let me know if clarifications are needed.

 

Thank you!

 

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.