MYSQL删除记录

时间:2013-05-20 15:41:33

标签: mysql sql

嗨,你们做了一些更多的修改,如何做到以下几点:

删除属于“A Wilks”的甲壳虫

person (driver-id, name, address)
car (license, model, year)
accident (report-number, date, location)
owns (driver-id, license) 
participated (driver-id, car, report-number, damage-amount)

这是我想出的:

DELETE FROM car
WHERE model = 'beetle'

然而我知道这是错误的,因为它会删除所有的甲壳虫汽车,而不仅仅是A Wilks所拥有的汽车。

6 个答案:

答案 0 :(得分:5)

DELETE FROM car
WHERE model = 'beetle'
AND license = (
    SELECT o.license from owns o INNER JOIN person p
    ON o.driver-id = p.driver-id
    WHERE p.name = 'A Wilks'
)

答案 1 :(得分:1)

DELETE FROM car
WHERE model = 'Beetle' AND license IN (
  SELECT license
  FROM owns
  INNER JOIN Person ON owns.driver_id = person.driver_id
  WHERE person_name = 'A Wilks'

如果您确定只有一个甲壳虫属于“A Wilks”,您可以在查询的第二行使用license =代替license IN

请考虑坐下来复制MySQL并尝试一些查询;你会更好地学习这些材料:)

答案 2 :(得分:0)

DELETE FROM car 
USING car 
INNER JOIN owns 
INNER JOIN person
WHERE car.license=owns.license 
AND car.model='Beetle'
AND owns.driver-id=person.driver-id 
AND person.name='A Wilks';

http://dev.mysql.com/doc/refman/5.0/en///delete.html

答案 3 :(得分:0)

delete from car where model ='beetle' and licence=(select licence owns INNER JOIN Person ON owns.driver_id = person.driver_id WHERE person_name = 'A Wilks')

答案 4 :(得分:0)

Philippinedev给出的答案很好,我想说明为什么它比使用子查询的答案更好。

他的回答使用了连接语法(最佳性能和控制):

DELETE FROM car 
USING car 
INNER JOIN owns 
INNER JOIN person
WHERE car.license=owns.license 
AND car.model='Beetle'
AND owns.driver-id=person.driver-id 
AND person.name='A Wilks';

他正在使用对连接表执行查询的语法,并从DELETE FROM子句中删除表中的所有匹配记录。替代方法使用子查询格式(易于编码,性能较差):

DELETE FROM car
WHERE model = 'beetle'
AND license = (
    SELECT o.license from owns o INNER JOIN person p
    ON o.driver-id = p.driver-id
    WHERE p.name = 'A Wilks'
)

子查询的性能比直接连接更昂贵。如果这是在真实的机动车系统系统上运行的查询(具有数百万条记录),您可能希望不惜一切代价避免使用子查询,而是使用直接连接。

答案 5 :(得分:-3)

我建议您将所有者添加到汽车并执行:

DELETE FROM car
WHERE model = 'beetle' and owner = 'ownername'

除非您owner中包含car,否则无效。