使用InnerJoin Firebird删除语句

时间:2016-11-25 12:56:23

标签: sql firebird

我创建了这个select语句来查找要删除的重复行。我虽然我只是改变SELECT to DELETE并删除行,但它没有。

这是select语句:

select * FROM MYCARD T1
INNER JOIN( SELECT IDCARD, YEAR, MONEY FROM MYCARD GROUP BY IDCARD, YEAR, MONEY HAVING COUNT(IDCARD) > 1 ) T2 ON
T1.IDCARD = T2.IDCARD AND T1.YEAR=T2.YEAR
AND T1.MONEY = T2.MONEY
WHERE T1.IDMONEY = 5 AND IDCARD=80
AND ID not in (select min(ID)
from MYCARD
WHERE IDMONEY=5
AND IDCARD=80
group by IDCARD, YEAR);

我想用这个删除:

DELETE FROM MYCARD T1
INNER JOIN( SELECT IDCARD, YEAR, MONEY FROM MYCARD GROUP BY IDCARD, YEAR, MONEY HAVING COUNT(IDCARD) > 1 ) T2 ON
T1.IDCARD = T2.IDCARD AND T1.YEAR=T2.YEAR
AND T1.MONEY = T2.MONEY
WHERE T1.IDMONEY = 5 AND IDCARD=80
AND ID not in (select min(ID)
from MYCARD
WHERE IDMONEY=5
AND IDCARD=80
group by IDCARD, YEAR);

但它不起作用。有什么想法吗?

我也试过这个:

DELETE FROM MYCARD
WHERE EXISTS (select * FROM MYCARD T1
INNER JOIN( SELECT IDCARD, YEAR, MONEY FROM MYCARD GROUP BY IDCARD, YEAR, MONEY HAVING COUNT(IDCARD) > 1 ) T2 ON
T1.IDCARD = T2.IDCARD AND T1.YEAR=T2.YEAR
AND T1.MONEY = T2.MONEY
WHERE T1.IDMONEY = 5 AND IDCARD=80
AND ID not in (select min(ID)
from MYCARD
WHERE IDMONEY=5
AND IDCARD=80
group by IDCARD, YEAR))

1 个答案:

答案 0 :(得分:4)

它不起作用,因为联接不属于Firebird delete syntax

您需要使用存在的删除,例如

delete from mycard t1
where exists (
   <a correlated subquery to identify the rows to delete>
)

或类似的方法来识别要删除的记录。底线是:所有必要的逻辑都需要在where子句中。

举个例子,你需要做类似的事情:

DELETE FROM MYCARD T1
WHERE T1.IDMONEY = 5 AND T1.IDCARD = 80
AND EXISTS (
    SELECT IDCARD, YEAR, MONEY 
    FROM MYCARD T2
    WHERE T2.IDCARD = T1.IDCARD 
    AND T2.YEAR = T1.YEAR
    AND T2.MONEY = T1.MONEY
    GROUP BY T2.IDCARD, T2.YEAR, T2.MONEY 
    HAVING COUNT(T2.IDCARD) > 1
)
AND T1.ID not in (
    select min(ID)
    from MYCARD
    WHERE IDMONEY = 5
    AND IDCARD = 80
    group by IDCARD, YEAR
)

您可能需要在“存在”中的选择中添加其他AND T2.IDMONEY = 5(除非moneyidmoney相同)。