简体   繁体   English

如何从MySQL中的两个不同表中删除重复的字段

[英]How to delete duplicated fields from two different tables in MySQL

Imagine that you have two tables. 想象一下,你有两张桌子。

Table bar: 表格栏:

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+

Table foo: 表foo:

+------------------+--------------+------+-----+---------+-------+
| Field            | Type         | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+-------+
| name_alternative | varchar(255) | YES  |     | NULL    |       |
+------------------+--------------+------+-----+---------+-------+

And you want to remove the rows from table bar that have the same name value as the field name_alternative from table foo 并且您希望从表格bar删除与表格foo的字段name_alternative具有相同name值的行

I could use the following query: 我可以使用以下查询:

DELETE FROM foo WHERE name IN (SELECT name_alternative FROM bar);

But this takes a very long time to execute having a large amount of records in both tables. 但这需要很长时间才能在两个表中执行大量记录。

So I was wondering if there is a better alternative to this query. 所以我想知道这个查询是否有更好的替代方案。

This is another way that would work, and I think it would be more efficient: 这是另一种可行的方式,我认为它会更有效:

DELETE FROM bar
    USING foo, bar
    WHERE name_alternative = name

Here is a working SQLFiddle example . 这是一个有效的SQLFiddle示例

See the documentation for delete . 请参阅文档以进行删除

Besides @dan1{4} answer, my guess is that it takes a long time because there is no index on bar(name) . 除了@ dan1 {4}之外,我的猜测是需要很长时间,因为bar(name)上没有索引。

You don't need an index covering the whole 255 chars, depending on your strings, ie if the first characters are different on a lot of rows, create an index on a few characters 您不需要覆盖整个255个字符的索引,具体取决于您的字符串,即如果许多行中的第一个字符不同,则在几个字符上创建索引

CREATE INDEX indexname ON bar(name(8))

8 is a suggested value that you may want to refine. 8是您可能想要优化的建议值。 The index will help mysql to locate each bar row that matches a foo.namealternative 索引将帮助mysql找到与foo.namealternative匹配的每个bar

delete from bar
using (
    select foo.name_alternative
    from 
        bar
        inner join
        foo on bar.name = foo.name_alternative
) s
where bar.name = s.name_alternative

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM