DELETE - INNER JOIN - 子查询

时间:2014-06-25 12:30:31

标签: mysql sql inner-join delete-row

我有3张桌子,你可以看到: enter image description here

所有3个表之间的关系:

  • cal_events.id = cf_cal_events.model_id
  • cf_cal_events.col_10 = source.ID_ELEMENT

如果cal_events

,我想删除cf_cal_eventsASUPPRIMER = '1'的数据

我知道这不是很难,但我对JOINS和子查询不是很熟悉,但是我试图为cal_events做这件事:

DELETE FROM cal_events
INNER JOIN cf_cal_events ON cal_events.id = cf_cal_events.model_id
INNER JOIN source ON cf_cal_events.col_10 = source.ID_ELEMENT
WHERE source.ASUPPRIMER = '1';

DELETE FROM cal_events
WHERE cal_events.id IN (
    SELECT cf_cal_events.model_id AS cal_events.id
    FROM cf_cal_events
    WHERE cf_cal_events.col_10 IN (
        SELECT ID_ELEMENT AS cf_cal_events.col_10
        FROM source
        WHERE source.ASUPPRIMER = '1'
    )
);

3 个答案:

答案 0 :(得分:1)

我将假设您的查询是正确的。您只需要将别名添加到delete语句中:

DELETE cal_events, cf_cal_events
    FROM cal_events INNER JOIN
         cf_cal_events
         ON cal_events.id = cf_cal_events.model_id INNER JOIN
         source
         ON cf_cal_events.col_10 = source.ID_ELEMENT
WHERE source.ASUPPRIMER = '1';

答案 1 :(得分:1)

docs查找multi table syntax。像这样的东西

DELETE cal_events,
       cf_cal_events
  FROM cal_events
  JOIN cf_cal_events 
    ON cal_events.id = cf_cal_events.model_id
  JOIN source 
    ON cf_cal_events.col_10 = source.ID_ELEMENT
 WHERE source.ASUPPRIMER = '1';

答案 2 :(得分:1)

您的问题有一个很好的例子: How to Delete using INNER JOIN with SQL Server?

在我看来应该是这样的:

DELETE cal_events, cf_cal_events
FROM cal_events
INNER JOIN cf_cal_events ON cal_events.id = cf_cal_events.model_id
INNER JOIN source ON cf_cal_events.col_10 = source.ID_ELEMENT
WHERE source.ASUPPRIMER = '1';