删除与其他表关系的行

时间:2013-05-02 10:24:46

标签: mysql

如果我有以下表格:

Product
+----+------+
| id | name |
+----+------+
|  1 | box  |
|  2 | car  |
|  3 | ball |
+----+------+

Color
+----+-------+
| id | name  |
+----+-------+
|  1 | red   |
|  2 | green |
|  3 | blue  |
+----+-------+

Size
+----+--------+
| id | number |
+----+--------+
|  1 |      1 |
|  2 |      5 |
|  3 |     10 |
+----+--------+

Color Options (#product | #color)
+---------+-------+
| product | color |
+---------+-------+
|       1 |     1 |
|       1 |     3 |
|       3 |     1 |
|       3 |     2 |
|       2 |     3 |
+---------+-------+

Size Options (#product | #size)
+---------+-------+
| product | color |
+---------+-------+
|       1 |     1 |
|       1 |     2 |
|       3 |     1 |
|       3 |     2 |
|       2 |     2 |
|       2 |     3 |
+---------+-------+

当我删除产品时,删除颜色和大小关系的最佳方法是什么?我是否需要在每个表格中进行删除或有任何自动过程?

3 个答案:

答案 0 :(得分:5)

您是否为mysql设置了正确的 RELATIONSHIP ? 你可以参考这个问题 How to create relationships in MySQLMySQL foreign key constraints, cascade delete

答案 1 :(得分:1)

CREATE TABLE SIZE_OPTIONS(PRODUCT REFERENCES PRODUCT(ID), COLOR REFERENCES COLOR_OPTIONS(COLOR) ON DELETE CASCADE);

对COLOR OPTIONS使用相同类型的语句。

答案 2 :(得分:-1)

INNER JOIN是一个答案

DELETE
FROM Product p
  INNER JOIN Color_Options co
    ON co.product = p.id
  INNER JOIN Color c
    ON co.color = c.id
  INNER JOIN Size_Options so
    ON co.product = p.id
  INNER JOIN Size s
    ON so.color = s.id