如何加入具有2个主键的SQL表内容?

时间:2014-06-15 09:58:44

标签: php mysql sql join

我的数据库中有两个SQL表

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

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

在这两个表格中,主键为customer_idbill_date,因为在特定月份,只有与单个客户相对应的帐单。

现在,我的问题是,我无法将这些表数据合并为一个以显示整个记录。

我试过这个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())

它没有给我准确的结果

2 个答案:

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

答案 1 :(得分: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