[英]Left outer join in MySQL
Is it possible to join these two tables to get the following result. 是否可以将这两个表连接起来以获得以下结果。
Table Stats
Date Cus_ID Pur Amount 2015-02-01 2585711 2 100 2015-02-02 2585711 5 250 2015-05-03 2585711 8 400 2015-02-01 2585475 2 100 2015-02-02 2585475 5 250 2015-05-03 2585475 8 400
Table Customer Reg_Date Cus_ID Gender Country 2014-04-11 2585711 Male Sweden 2015-02-01 2585475 Female Sweden
Expected Result Date Cus_ID Pur Amount Gender Country 2014-04-11 2585711 NULL NULL Male Sweden 2015-02-01 2585711 2 100 Male Sweden 2015-02-02 2585711 5 250 Male Sweden 2015-05-03 2585711 8 400 Male Sweden 2015-02-01 2585475 2 100 Female Sweden 2015-02-02 2585475 5 250 Female Sweden 2015-05-03 2585475 8 400 Female Sweden
if I use a left outer join to join the two tables, I get the following result Date Cus_ID Pur Amt Gender Country 2015-02-01 2585711 2 100 Male Sweden 2015-02-02 2585711 5 250 Male Sweden 2015-05-03 2585711 8 400 Male Sweden 2015-02-01 2585475 2 100 Female Sweden 2015-02-02 2585475 5 250 Female Sweden 2015-05-03 2585475 8 400 Female Sweden
My query: Select if(a.Date IS NULL,b.reg_date,a.date) as Date, b.cus_id, pur, Amount, gender, country from (Select * from stats) as a Left outer join (select * from customer) as b on a.cus_id = b.cus_id
Any help will be highly appreciated. 任何帮助将不胜感激。 Thanks!
谢谢!
I don't know if this is still relevant. 我不知道这是否仍然有意义。
If the idea to show every date a customer was active, even if they didn't make a purchase, I'd start with a table that gives me all dates and customer pairs first. 如果要显示客户活动的每个日期的想法,即使他们没有购物,我也会从一个表格开始,该表格首先列出所有日期和客户对。
select [date],[cust_id]
into #activity
from stats
union
select [reg_date],[cust_id]
from customer
select t1.*, t2.pur, t2.amt
from #activity t1
left outer join stats t2 on
t1.[date] = t2.[date] and t1.[cust_id] = t2.[cust_id]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.