3

我正在做更多的修改,如何执行以下操作:

删除属于“A Wilks”的甲壳虫</p>

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 拥有的那辆。

4

6 回答 6

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'
)
于 2013-05-20T15:46:12.723 回答
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 的副本并尝试一些查询;你会更好地学习材料:)

于 2013-05-20T15:46:52.020 回答
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')

于 2013-05-20T16:09:11.203 回答
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

于 2013-05-20T15:52:57.617 回答
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'
)

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

于 2013-05-20T17:21:23.440 回答
-3

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

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

除非您owner包含在car.

于 2013-05-20T15:46:01.877 回答