MYSQL union和left join没有返回任何结果

时间:2015-01-26 17:21:14

标签: mysql

我有工会从各种表中获取数据,我想要做的是加入一个单独的查询(如下所示)并在电子邮件上匹配。有些事情并不完全正确,因为它根本不会返回任何结果。两个查询都独立工作。我想要左边的工会和右边的任何比赛的所有内容。

帮助表示赞赏..

SELECT * 
FROM   (SELECT DISTINCT email_address AS email, 
                title, 
                forename      AS first_name, 
                surname       AS last_name, 
                'wifi'        AS source, 
                postcode      AS postcode 
FROM   source1 
UNION 
SELECT DISTINCT email, 
                title, 
                first_name, 
                last_name, 
                'chauntry' AS source, 
                post_code  AS postcode 
FROM   source2 
WHERE  mailing_indicator = 1) AS x 
LEFT JOIN (SELECT email, 
                 Avg(amount_paid)                AS avg_paid, 
                 Count(*)                        AS no_times_booked, 
                 Count(DISTINCT( Month(added) )) AS unique_months 
          FROM   chauntry 
          WHERE  added >= Now() - INTERVAL 1 year 
                 AND mailing_indicator = 1 
          GROUP  BY email) AS y 
          ON x.email = y.email      

这是粗略的数据模式

Source 1

email          | title | first_name | last_name | source

test1@test.com |   Mr  | name       | surname   | source1
test2@test.com |   Mr  | name       | surname   | source1
test3@test.com |   Mr  | name       | surname   | source1

联盟

来源2

email          | title | first_name | last_name | source

test4@test.com |   Mr  |   name     | surname   | source2
test5@test.com |   Mr  |   name     | surname   | source2
test6@test.com |   Mr  |   name     | surname   | source2

来源3(左连接)

email           | amount_paid | booking_date
test1@test.com  | 50.00       | 2010-01-13
test1@test.com  | 50.00       | 2010-01-13

寻找

email | title | first_name | last_name | source | avg_spend | number_bookings | unique_months

test1@test.com | Mr | name | surname | source1  | 50.00     |  2              | 1
test2@test.com | Mr | name | surname | source1
test3@test.com | Mr | name | surname | source1
test4@test.com | Mr | name | surname | source2
test5@test.com | Mr | name | surname | source2
test6@test.com | Mr | name | surname | source2

0 个答案:

没有答案