您的SQL语法有问题,但不知道原因

时间:2019-01-22 10:48:03

标签: mysql sql

INSERT INTO tkblue_tklabel_dev_archdata.EmailContent2016
(
    SELECT tkblue_tklabel_dev_data.EmailContent.*
    FROM tkblue_tklabel_dev_data.EmailContent
    LEFT JOIN tkblue_tklabel_dev_archdata.EmailTracking ON tkblue_tklabel_dev_archdata.EmailTracking.id = tkblue_tklabel_dev_data.EmailContent.idEmailParam
    WHERE (tkblue_tklabel_dev_archdata.EmailTracking.EmailDate <= "2016-12-31 23:59:59" and tkblue_tklabel_dev_archdata.EmailTracking.EmailDate >= "2016-01-01 00:00:00"); 
);
  

您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本,以使用正确的语法   在第6行的“”附近

我没有成功找到此错误的原因。

1 个答案:

答案 0 :(得分:-1)

INSERT中,括号应用于列出列,而不是用于生成数据的查询。

在这种情况下,您似乎知道数据具有相同的格式,所以不使用列列表也是可以的-尽管create table asinsert更好。

无论如何:

INSERT INTO tkblue_tklabel_dev_archdata.EmailContent2016
    SELECT ec.*
    FROM tkblue_tklabel_dev_data.EmailContent ec JOIN
         tkblue_tklabel_dev_archdata.EmailTracking et
         ON et.id = ec.idEmailParam
    WHERE et.EmailDate < '2017-01-01' AND
          et.EmailDate >= '2016-01-01';

我还介绍了表别名,这使查询更易于编写和读取。这也简化了日期逻辑。

这还将JOIN更改为内部联接-WHERE子句仍会这样做。

为防止由JOIN引起的重复,我改用EXISTS

INSERT INTO tkblue_tklabel_dev_archdata.EmailContent2016
    SELECT ec.*
    FROM tkblue_tklabel_dev_data.EmailContent ec
    WHERE EXISTS (SELECT 1           
                  FROM tkblue_tklabel_dev_archdata.EmailTracking et
                  WHERE et.id = ec.idEmailParam AND
                        et.EmailDate < '2017-01-01' AND
                        et.EmailDate >= '2016-01-01'
                 );