Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

mysql - SQL Query with union and join

my set-up is like this

Table1: company_group - company_id, company_name
Table2: store         - store_id, store_name
Table3: sales         - sales_id, company_id, store_id, date, sales
Table4: wh_sales      - wh_sale_id, company_id, store_id, date, sales

Table5: purchase      - purchase_id, company_id, store_id, date, purchase

Now I am able to get the data for the first four tables using the select and union query, but I can't make out how and which join I should use to get the data for the table5 in the same table

I am using the query for the first four tables like

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`sales`.`sales` 
from company_group, store,sales
where `company_group`.`company.id`=`sales`.`company.id`
and `store`.`store.id`=`sales`.`store.id`
group by company_name,store_name, 'MONTH'

UNION

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`wh_sales`.`sales`
from company_group, store,wh_sales
where `company_group`.`company.id`=`wh_sales`.`company.id`
and `store`.`store.id`=`wh_sales`.`store.id`
group by company_name,store_name, 'MONTH'

now how can I include the Table5 so that I can get the result like

company_name store_name   month      sales    purchase
company-a     store-c    December    40000    45000
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following query

select `company_name, `store_name`, MONTH, sum(`sales`) as sales, sum(purchase) as purchase   from (
select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`sales`.`sales` , 0 as purchase
from company_group, store,sales
where `company_group`.`company.id`=`sales`.`company.id`
and `store`.`store.id`=`sales`.`store.id`

UNION

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`wh_sales`.`sales`, 0 as purchase
from company_group, store,wh_sales
where `company_group`.`company.id`=`wh_sales`.`company.id`
and `store`.`store.id`=`wh_sales`.`store.id`

UNION

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH, 0 as sales, purchase
from company_group, store,purchase
where `company_group`.`company.id`=`purchase`.`company.id`
and `store`.`store.id`=`purchase`.`store.id`) a
group by company_name,store_name, 'MONTH'

The group by clause is not needed for the inner queries since there is no group function. I have moved it to the outermost query


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...