views:

67

answers:

3

Is it possible to make multiple queries at once within the same query?

Here is an example of what I'm trying to do.

We have the following table:

| userid | price | stock | description | 
----------------------------------------
  1        10.00   5       some text 
  2        25.00   2       some text
  3        15.00   3       some text
  4        35.00   2       some text
  5        30.00   4       some text

The queries that I'm trying to do are:

  1. the MIN and MAX price group by description
  2. the price set by userid 2
  3. Stock and price of the first three results only without grouping

So the HTML table will look like this:

description | Min_Price | Max_Price | Price Set by userid 2 | 1st Price | 1st Stock | 2nd Price | 2nd Stock | 3rd Price | 3rd Stock
A: 

MySQL Unions (http://dev.mysql.com/doc/refman/5.0/en/union.html) should probably put you on the right track.

You could also do most of it with sub selects, though that is probably not a great idea.

Glenn Condron
why with sub selects will not be a great idea?
Ole Media
A: 

Use union or, to have everything in one row, something like that:

Select 
 (Select min(price) from table) as min_price, 
 (Select max(price) from table) as max_price,
 ....
Michal Dymel
A: 

This solution will require a number of "sub queries" or joins.

You are probably looking at something like:

select t1.description, 
       t1.min_price,
       t1.max_price,
       t2.user_id_2_price 
from
  (select description, min(price) as min_price, max(price) as max_price from t group by description) t1 
left join
  (select price, description as user_id_2_price from t where userid = '2') t2
on
  (t1.description = t2.description)

And you can add as many of these "left joins" as you need

Michael
Running this query I get:Unknown column 't2.description' in 'on clause'
Ole Media
Sorry... I forgot to give an alias to the result set, made the change in the code now
Michael