【问题标题】:Can't use ALIAS in delete statement in MARIA DB不能在 MARIADB 的删除语句中使用 ALIAS
【发布时间】:2020-03-02 20:02:25
【问题描述】:

我试图从表中删除欺骗,但它不允许我使用别名。 尝试了多个论坛中提供的各种解决方案。

查询是,

DELETE FROM `table` AS t1
        WHERE EXISTS (
         SELECT 1 FROM `table` AS t2
         WHERE t2.`col1` = t1.`col1`
         AND t2.`col2` = t1.`col2`
         AND t2.id > t1.id )

【问题讨论】:

    标签: mysql mariadb mariasql


    【解决方案1】:

    您可以尝试使用内部连接而不是存在子查询

    DELETE t
    FROM `billing_squarecustomer` t
    INNER JOIN  (
       SELECT  t2.`patient_id`.
       FROM `billing_squarecustomer` AS t2
       INNER JOIN `billing_squarecustomer` AS t1
       WHERE t2.`patient_id` = t1.`patient_id`
       AND t2.`merchant_id` = t1.`merchant_id`
       AND t2.id > t1.id
    ) tdel = tdel.patient_id = t.patient_id
    

    【讨论】:

      【解决方案2】:

      可以使用多表DELETE语句:

      DELETE t1 
      FROM `table` t1
      JOIN `table` t2 ON t2.col1 = t1.col1 AND t2.col2 = t1.col2 AND t2.id > t1.id
      

      【讨论】:

        【解决方案3】:

        idprimary key时,可以使用left join删除同一张表中的重复项

        delete t1
        from `table` as t1
        left join `table` as t2 on t1.col1 = t2.col1 and t1.col2 = t2.col2 and t1.id < t2.id
        where t2.id is not null;
        

        【讨论】:

          【解决方案4】:

          你可以试试这个,它更复杂但更安全,因为使用内部删除可能非常危险,这样你可以先检查你想删除的内容:

          SET @discriminator = 0;
          SET @p1 = null;
          SET @p2 = null;
          
          CREATE TEMPORARY TABLE temp_rows(
              `id` INT PRIMARY KEY,
              `index` INT,
              `col1` COL1TYPE,
              `col2` COL2TYPE
          );
          
          INSERT INTO temp_rows (`index`, `col1`, `col2`, `id`)
          SELECT CASE WHEN @p1 != col1 OR @p2 != col2 THEN @discriminator := 0 ELSE @discriminator := @discriminator + 1 END AS 'index', 
              @p1 := col1 AS 'col1', 
              @p2 := col2 AS 'col2',
              id
          FROM `schema`.table
          ORDER BY col1, col2, id desc;
          
          DELETE FROM table WHERE EXISTS (
               SELECT 1 FROM `temp_rows`
               WHERE table.`id` = temp_rows.`id`
          );
          
          DROP TEMPORARY TABLE temp_rows;
          

          【讨论】:

            猜你喜欢
            • 2016-07-24
            • 2012-07-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多