Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can join a query result set with an existing table?

Tags:

sql

mysql

is there any way to avoid using tmp table?

I am using a query with aggregate function (sum) to generate the sum of each product: the result looks like this:

product_name | sum(qty) 
product_1    | 100 
product_2    | 200 
product_5    | 300 

now i want to join the above result to another table called products. so that i will have a summary like this:

product_name | sum(qty) 
product_1    | 100 
product_2    | 200 
product_3    | 0 
product_4    | 0 
product_5    | 300 

i know 1 way of doing this is the dump the 1st query result to a temp table then join it with products table. is there a better way?

like image 422
Yang Avatar asked Apr 05 '10 03:04

Yang


People also ask

Can you join a table with a query?

Note: You can join queries in the same way that you join tables, and can also join both.

How do I join two queries in the same table?

Use the UNION ALL clause to join data from columns in two or more tables. In our example, we join data from the employee and customer tables. On the left of the UNION ALL keyword, put the first SELECT statement to get data from the first table (in our example, the table employee ).


4 Answers

SELECT Product_Name, Total FROM ProductTable x
LEFT OUTER JOIN (SELECT SUM(qty) as Total, ProductID FROM InventoryTable 
    GROUP BY ProductID) y
ON x.ProductID = y.ProductID
like image 62
egrunin Avatar answered Oct 01 '22 09:10

egrunin


You can do it like this

select table1.productname, virtualtable.qty
from table1 
inner join (
  select productid, qty
  from table2
  group by productid
) as virtualtable on virtualtable.productid = table1.productid
like image 28
codingguy3000 Avatar answered Oct 01 '22 09:10

codingguy3000


Perhaps the UNION syntax is what you are looking for? http://dev.mysql.com/doc/refman/5.0/en/union.html Some more information would be useful.

like image 25
Rob Van Dam Avatar answered Oct 01 '22 10:10

Rob Van Dam


You can do multiple joins in one select query. Does that solve your problem? It's hard to tell what you are asking for.

like image 42
Mike Daniels Avatar answered Oct 01 '22 11:10

Mike Daniels