2011-12-03 178 views
0

我在數據庫中使用兩個表。這些表是這樣的:Mysql加入查詢

表A:

id | date 
---------------------- 
    12001 | 2011-01-01 
    13567 | 2011-01-04 
    13567 | 2011-01-04 
    11546 | 2011-01-07 
    13567 | 2011-01-07 
    18000 | 2011-01-08 

表B:

user | date  | amount 
---------------------------------- 
    15467 | 2011-01-04 | 140 
    14568 | 2011-01-04 | 120 
    14563 | 2011-01-05 | 140 
    12341 | 2011-01-07 | 140 
    18000 | 2011-01-08 | 120 

我需要一個查詢,將連接這兩個表。

第一個查詢應該導致表A中按用戶分組的用戶總數以及按日期分組的表A中唯一用戶的數量。該查詢看起來像:

SELECT COUNT(DISTINCT id) AS uniq, COUNT(*) AS total, format_date(date, '%Y-%m-%d') as date FROM A GROUP BY date 

從第二張表格,我需要按日期分組的量的總和。 該查詢看起來像:

SELECT SUM(amount) AS total_amount FROM B GROUP BY DATE_FORMAT(date, '%Y-%m-%d') 

我想要做的就是這兩個查詢合併成一個上欄「日期」,並作爲一個結果,我得到以下列表:

date  | unique | total | amount 
----------------------------------------------- 
2011-01-01 |  1  |  1 |  0 
2011-01-04 |  1  |  2 | 260 
2011-01-05 |  0  |  0 | 140 
2011-01-07 |  2  |  2 | 140 
2011-01-08 |  1  |  1 | 120 

我如何使用一個查詢來做到這一點? 感謝您的所有建議。

回答

0
select date_format(a.date, '%Y-%m-%d') as date, a.uniq, a.total, ifnull(b.amount, 0) as amount 
from ( 
    select count(distinct id) as uniq, count(*) as total, date 
    from tablea 
    group by date 
) a 
left join (
    select sum(amount) as amount, date 
    from tableb 
    group by date 
) b on a.date = b.date 
order by a.date 

我假定字段date是一個datetime類型。最好在最終結果集中格式化輸出字段(在這種情況下爲date字段)。

您的查詢很好,他們需要的是一個join