2014-06-15 28 views
1

我在我的數據庫中的兩個SQL表如何加入SQL表有2個主鍵的內容?

表1的結構,即customer_classification是表2的

CREATE TABLE IF NOT EXISTS `customer_classification` (
    `sid` int(5) NOT NULL, 
    `customer_id` varchar(15) NOT NULL, 
    `classification` varchar(5) NOT NULL, 
    `appendix_id` int(5) NOT NULL, 
    `bill_date` date NOT NULL); 

結構即customer_consumption

CREATE TABLE IF NOT EXISTS `customer_consumption` 
    `sid` int(5) NOT NULL, 
    `customer_id` varchar(25) NOT NULL, 
    `bill_date` date NOT NULL, 
    `reading` float NOT NULL, 
    `consumption` float NOT NULL, 
    `energy_bill` float NOT NULL, 
    `meter_rent` float NOT NULL, 
    `arrear` float NOT NULL); 

在這兩個表中s,主鍵爲customer_idbill_date,因爲在某個月份只有單一客戶的賬單。

現在,我的問題是,我無法將這些表數據合併爲一個來顯示整個記錄。

我已經試過這個SQL查詢,看看

select co.customer_id, co.reading, co.consumption, cl.classification 
from customer_consumption as co 
INNER JOIN customer_classification as cl 
    on cl.customer_id = co.customer_id 
     and month(cl.bill_date) = month(co.bill_date) 
where month(co.bill_date) = month(now()) 

它不給我準確的結果

+1

什麼是你想要得到的,什麼是你,而不是結果的結果呢?另外,你使用的是MySQL還是Oracle ...不能兼得,對吧? –

+0

請提供您的兩個表格的樣本數據,並提供獲取結果和接受的數據 –

+0

您需要包括年份和月份。 –

回答

0

我要去猜測,消耗表中,每個月份和分類記錄記錄只有在分類更改時纔有記錄。如果是這樣,你想獲得最新的分類。你能做到這一點的:

select co.customer_id, co.reading, co.consumption, 
     (select cl.classification 
     from customer_classification as cl 
     where cl.customer_id = co.customer_id and 
       cl.bill_date <= co.bill_date 
     order by cl.bill_date desc 
     limit 1 
     ) as classification 
from customer_consumption co 
where month(co.bill_date) = month(now()); 
0

試試這個SQL查詢

select co.customer_id, sum(co.reading), sum(co.consumption), cl.classification 
from customer_consumption as co 
INNER JOIN customer_classification as cl 
    on cl.customer_id = co.customer_id 
     and month(cl.bill_date) = month(co.bill_date) 
where month(co.bill_date) = month(now()) 
group by co.customer_id