【问题标题】:Copy data from one table to another with specific condition将数据从一个表复制到另一个具有特定条件的表
【发布时间】:2019-11-29 15:54:36
【问题描述】:

我想将数据从一个表复制到另一个表,但仅在特定日期之后的列值中有processed='1'。

我有可以做到的代码,但它需要很长时间才能执行。

"INSERT INTO eamglo5_billingsystem.`consignment` ( 
`consignment_status`,
  `account`,
  `awb`,
  `hawb`,
  `service`,
  `handling`,
  `reference`,
  `date_submitted`,
  `date_imported`,
  `date_printed`,
  `printed_file_id`,
  `date_received`,
  `date_booked`,
  `booked_file_id`,
  `date_exported`,
  `export_file_id`,
  `company`,
  `contact`,
  `address_line_1`,
  `address_line_2`,
  `address_line_3`,
  `id`
)
     SELECT
        'Y',
       `account`,
      `awb`,
      `hawb`,
      `service`,
      `handling`,
      `reference`,
      `date_submitted`,
      `date_imported`,
      `date_printed`,
      `printed_file_id`,
      `date_received`,
      `date_booked`,
      `booked_file_id`,
      `date_exported`,
      `export_file_id`,
      `company`,
      `contact`,
      `address_line_1`,
      `address_line_2`,
      `address_line_3`,
      `id` 
      FROM  `eamglo5_singaporelive`.`consignment` 
      left join  (
        SELECT eamglo5_billingsystem.`consignment`.`id` as id1 
         FROM eamglo5_billingsystem.`consignment` 
      ) t  ON  `eamglo5_singaporelive`.`consignment`.id >id1
      WHERE `eamglo5_singaporelive`.`consignment`.`processed`=1 
       and `eamglo5_singaporelive`.`consignment`.date_booked>'2018-07-17'

预期:应将 eamglo5_singaporelive.consignment 表中的数据复制到 eamglo5_billingsystem.consignment 表中,其中仅处理 =1 个值。

实际:花费无限时间来执行和获取行。

【问题讨论】:

  • 请解释您尝试实施的条件。您的问题中没有任何内容可以解释您为什么拥有LEFT JOIN
  • 条件为eamglo5_singpaorelive.consignment.processed='1' and date_booked>'2019-07-19'。一旦工作,我将每隔 10 分钟左右执行此查询以将行插入 eamglo5_billingsystem。
  • 问题是选择需要无限的时间来执行。

标签: mysql sql


【解决方案1】:

您的 LEFT JOIN 条件为 consignment.id >id1 几乎是在创建一个 catesian 产品。您可能想要的是,只插入源表中id 比目标表中最高id1 更高的行。您应该改用 SELECT MAX(id) 子查询:

SELECT [..]
FROM  `eamglo5_singaporelive`.`consignment` 
WHERE `eamglo5_singaporelive`.`consignment`.`processed`=1 
  and `eamglo5_singaporelive`.`consignment`.date_booked>'2018-07-17'
  and `eamglo5_singaporelive`.`consignment`.id > (
     SELECT MAX(id1) FROM eamglo5_billingsystem.`consignment`
  )

【讨论】:

    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2021-12-12
    • 2012-11-24
    相关资源
    最近更新 更多