【问题标题】:How to Join SQL Table Content having 2 primary keys?如何加入具有 2 个主键的 SQL 表内容?
【发布时间】:2014-06-15 09:58:43
【问题描述】:

我的数据库中有两个 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())

它没有给我准确的结果

【问题讨论】:

  • 你想得到什么结果,你得到的结果又是什么?另外,您使用的是 MySQL 还是 Oracle...不能同时使用,对吗?
  • 请提供您的两个表的示例数据,并提供获取结果和接受的数据
  • 您需要包括年份和月份。
  • 这里是sql表[csv]格式数据的链接[drive.google.com/…
  • 没有人会在谷歌驱动器中查找。取出一些示例数据并发布在您的问题中。

标签: php mysql sql join


【解决方案1】:

我猜测消费表有每个月的记录,而分类记录只有当分类发生变化时才有记录。如果是这样,您希望获得最新的分类。你可以这样做:

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

【讨论】:

    【解决方案2】:

    试试这个 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      相关资源
      最近更新 更多