从同一表和其他表中进行选择所指定的表中删除行(内部联接)

时间:2019-06-06 11:21:49

标签: mysql sql-delete

我需要从数据库中删除一些行,这些行是使用选择sql语句选择的

我尝试使用别名,但是它们也没有作用

DELETE FROM OBSERVATION WHERE OBSERVATION.ID in
(SELECT OBSERVATION.ID from OBSERVATION
inner join SPECIMEN on SPECIMEN.ID=OBSERVATION.SPECIMEN_ID
WHERE SPECIMEN.GENDER="male"and OBSERVATION.VALUE_TERM is not null and OBSERVATION.PARAMETER_STABLE_ID="IMPC_PAT_028_002")

我总是会收到错误:

  

查询(1093)中的错误:您无法在FROM子句中指定目标表'OBSERVATION'进行更新

3 个答案:

答案 0 :(得分:0)

Mysql不允许使用与用于选择要删除的行的表相同的表进行删除,为避免这种情况,您必须构建一组与原始表无关的行

您可以在子查询上使用内部联接,而不是在子句中使用
这应该足够了

DELETE 
FROM OBSERVATION 
INNER JOIN  (
    SELECT OBSERVATION.ID 
    from OBSERVATION
    inner join SPECIMEN on SPECIMEN.ID=OBSERVATION.SPECIMEN_ID
    WHERE SPECIMEN.GENDER="male"
    and OBSERVATION.VALUE_TERM is not null
     and OBSERVATION.PARAMETER_STABLE_ID="IMPC_PAT_028_002"
)  t  OBSERVATION.ID = t.ID 

否则,您需要以这种方式强制执行

DELETE 
FROM OBSERVATION 
INNER JOIN  (
  select id from( 
    SELECT OBSERVATION.ID 
    from OBSERVATION
    inner join SPECIMEN on SPECIMEN.ID=OBSERVATION.SPECIMEN_ID
    WHERE SPECIMEN.GENDER="male"
    and OBSERVATION.VALUE_TERM is not null
     and OBSERVATION.PARAMETER_STABLE_ID="IMPC_PAT_028_002"

     ) t1
)  t  OBSERVATION.ID = t.ID 

答案 1 :(得分:0)

假设observation.id是主键,为什么不使用:

DELETE o
  FROM observation o
  JOIN specimen s
    ON s.id = o.specimen_id
 WHERE s.gender = 'male' 
   AND o.value_term IS NOT NULL 
   AND o.parameter_stable_id = 'IMPC_PAT_028_002'

答案 2 :(得分:0)

DELETE targetTable
FROM targetTable
INNER JOIN otherTable
    ON targetTable.col = otherTable.col
WHERE otherTable.col2 = “foo”