MySQL删除具有引用不存在ID的参数的行

时间:2017-10-05 12:43:12

标签: mysql sql database exists

我需要从表中删除所有包含" for_id"的记录。参数是指" id"这个表中没有。

In this example,我需要删除name ="汤姆"因为id = 3的条目不存在。

谢谢!

3 个答案:

答案 0 :(得分:2)

因此,您希望remove for_id not existid keep的记录for_id 换句话说,exists id SELECT * FROM table_name where for_id in (select id from table_name) join SELECT t1.* FROM table_name t1 join table_name t2 on t1.for_id=t2.id

| id | for_id | lvl | name |
|----|--------|-----|------|
|  4 |      1 |   1 |  joe |
|  5 |      1 |   1 | mack |
|  6 |      5 |   2 | bill |
|  7 |      5 |   2 |  rex |
|  8 |      7 |   3 |  ted |

或使用date --date='last Monday' date --date='last week + last Thursday' date --date='last week + last Monday'

CREATE EXTERNAL TABLE IF NOT EXISTS abc ( mail string, Type string, Id bigint, Date string, LId bigint, value string)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES (
"column.xpath.OptOutEmail"="/Re/mail/text()",
"column.xpath.OptOutType"="/Re/Type/text()",
"column.xpath.SurveyId"="/Re/Id/text()",
"column.xpath.RequestedDate"="/Re/Date/text()",
"column.xpath.EmailListId"="/Re/Lists/LId/text()",
"column.xpath.Description"="/Re/Lists/value/text()")
STORED AS INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
LOCATION '/abc/xyz'
TBLPROPERTIES ("xmlinput.start"="<Out>","xmlinput.end"= "</Out>");

输出:

HtmlFieldPrefix

答案 1 :(得分:1)

如果你想删除那些for_id = 0的那个,你可以使用:

DELETE 
FROM table_name as t1
where not exists (select id 
       from table_name as t2 
       where t2.id=t1.for_id) 

如果你不想删除那些for_id = 0的你可以使用:

delete 
FROM table_name as t1
where not exists (select id 
       from table_name as t2 
       where t2.id=t1.for_id) and t1.for_id<>0

答案 2 :(得分:1)

DELETE D.* FROM table_name D
  LEFT JOIN table_name T
    ON T.ID=D.FOR_ID
 WHERE T.ID IS NULL and D.FOR_ID<>0;

sqlfiddle.com上进行测试