删除查询 - mysql

时间:2016-05-10 02:41:26

标签: mysql sql sql-delete

如果我有一张表,如:

Select ProductID, tblProduct.ProductType, Price, ((Price *.20)+Price) AS 'Increased Price'
From tblProduct join tblCompany
    On tblProduct.CompanyID = tblCompany.CompanyID
Where tblCompany.CompanyID IN
    (Select CompanyID
    From tblCompany
    Where City = 'Kalamazoo')
Order By ProductID

我需要的是删除包含name2 = E

的所有id行

如果我这样做:

     name1       |    name2     |    id     |
+----------------+--------------+-----------+
| A              | E            | 1         |
| A              | F            | 1         |
| B              | G            | 1         |
| C              | H            | 1         |
| D              | I            | 1         |
| A              | J            | 2         |
| B              | K            | 2         |
| C              | L            | 2         |
| D              | M            | 2         |
| A              | N            | 2         |

它只给了我这个

delete from table where name2 = E

我想要的结果是:

     name1       |    name2     |    id     |
+----------------+--------------+-----------+
| A              | F            | 1         |
| B              | G            | 1         |
| C              | H            | 1         |
| D              | I            | 1         |
| A              | J            | 2         |
| B              | K            | 2         |
| C              | L            | 2         |
| D              | M            | 2         |
| A              | N            | 2         |

我应该使用哪种查询?

1 个答案:

答案 0 :(得分:3)

我想你想要这样的东西:

delete t
    from table t join
         table t2
         on t.id = t2.id and t2.name2 = 'E';

这将删除表中与name2'E'的行共享ID的所有行。

在大多数其他数据库中,您可以写:

delete t from table t
    where t.id in (select t2.id from table t2 where t2.name2 = 'E');

使用exists类似的东西。不幸的是,MySQL不允许这种语法,因为子查询引用了被修改的表。有一个黑客:

delete t from table t
    where t.id in (select id from (select t2.id from table t2 where t2.name2 = 'E') t);

我更喜欢带join的版本。

对于select,我会这样做:

select t.*
from table t
where t.id in (select t2.id from table t2 where t2.name2 = 'E');

或:

select t.*
from table t
where exists (select 1 from table t2 where t2.name2 = 'E' and t2.id = t.id);