mysql - 组合两个查询时多次重复相同的值

标签 mysql mysql-workbench

我在执行洞查询时在mysql工作台中编写了两个查询,我得到了相同的值。我该怎么办?

这是我的查询

Select * 
from 
  (
    (select division.name,
            date(meter_data.reading_date),
            sum(meter_data.meter_delta) 'Gas Consumption (m3)'
     from meter, meter_data, division
     where meter.meter_id = meter_data.meter_id 
       and meter.division_id = division.division_id
       and Date(meter_data.reading_date) between '2018-04-01' and '2018-05-03' 
     group by date(meter_data.reading_date) 
    ) as table1,

    (Select Date(receipt.receipt_date), 
            sum(case receipt_item.item_name 
                    when 'Gas' then receipt_item.item_amount else 0 
                end) 'Gas Purchase'
     from receipt_item, receipt
     where receipt.receipt_id = receipt_item.receipt_id
       and Date(receipt.receipt_date) between '2018-04-01' and '2018-05-03'  
     group by Date(receipt.receipt_date)
    ) as table2
  );

单独执行查询时,每个查询返回精确的 33 行,但总共返回 1089 rwos

例如,我在这里得到相同数据的所有重复

enter image description here

但需要这样显示(这是演示图像) enter image description here

最佳答案

我的查询有一些问题,查询应该如下所示

Select * 
from 
  (
    (select division.name,
            date(meter_data.reading_date) AS reading_date,
            sum(meter_data.meter_delta) 'Gas Consumption (m3)'
     from meter, meter_data, division
     where meter.meter_id = meter_data.meter_id 
       and meter.division_id = division.division_id
       and Date(meter_data.reading_date) between '2018-04-01' and '2018-05-03' 
     group by date(meter_data.reading_date) 
    ) as table1,

    (Select Date(receipt.receipt_date) AS receipt_date, 
            sum(case receipt_item.item_name 
                    when 'Gas' then receipt_item.item_amount else 0 
                end) 'Gas Purchase'
     from receipt_item, receipt
     where receipt.receipt_id = receipt_item.receipt_id
       and Date(receipt.receipt_date) between '2018-04-01' and '2018-05-03'  
     group by Date(receipt.receipt_date)
    ) as table2
  )
WHERE table1.reading_date = table2.receipt_date;

这解决了我的问题

关于mysql - 组合两个查询时多次重复相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347664/

相关文章:

mysql - LONGTEXT 在 PGSQL 和 MySQL 的迁移中有效

mysql - 如何在 MySQL Workbench 中创建片段?

mysql - 如何创建通知 chrome 扩展?

大数据MySQL数据库设计

amazon-web-services - 无法将 MySQL Workbench 连接到 RDS 实例

MySQL Workbench 不提交更改

python - MySQL Workbench 无法编辑使用命令行创建的表

javascript - 如何关闭 mariadb 中的自动提交?

mysql - 使用 MySQL 和 Group By 进行划分

mysql - 是否可以选择 MySQL 中相似行的计数?