简体   繁体   English

如何联接具有2个主键的SQL表内容?

[英]How to Join SQL Table Content having 2 primary keys?

I have two SQL Tables in my database 我的数据库中有两个SQL表

Structure of table1 is ie customer_classification is table1的结构为,即customer_classification

 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 ); 

Structure of table2 is ie customer_consumption is table2的结构为,即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 ); 

In both tables, primary keys are customer_id and bill_date , because in a particular month there is only bill corresponding to single customer. 在这两个表中,主键分别是customer_idbill_date ,因为在特定月份中,只有对应于单个客户的账单。

Now, my problem is, I am not able to merge these tables data into one to display the whole record. 现在,我的问题是,我无法将这些表数据合并为一个以显示整个记录。

I have tried this Sql Query, have a look 我已经试过这个Sql Query,看看

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())

It is not giving me the accurate result 这没有给我准确的结果

I am going to guess that the consumption table has records for each month and the classification record only has records when the classification changes. 我猜想消费表有每个月的记录,而分类记录仅在分类更改时才有记录。 If so, you want to get the most recent classification. 如果是这样,则要获取最新的分类。 And you can do that as: 您可以这样做:

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());

Try this SQL query 试试这个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM