Mysql delete from не работает

MySQL DELETE FROM с подзапросом в качестве условия

Я пытаюсь сделать такой запрос:

Как вы, наверное, догадались, я хочу удалить родительское отношение к 1015, если у того же tid есть другие родители. Однако это дает мне синтаксическую ошибку:

Я проверил документацию и запустил подзапрос сам по себе, и, похоже, все прошло проверку. Кто-нибудь может понять, что здесь не так?

Обновление . Как указано ниже, MySQL не позволяет использовать таблицу, из которой вы удаляете, в подзапросе для условия.

9 ответов

Вы не можете указать целевую таблицу для удаления.

Для тех, кто считает, что этот вопрос хочет удалить при использовании подзапроса, я оставляю вам этот пример для перехвата MySQL (даже если некоторые люди думают, что это невозможно сделать):

Выдаст вам ошибку:

Однако этот запрос:

Будет работать нормально:

Оберните свой подзапрос в дополнительный подзапрос (здесь с именем x), и MySQL с радостью сделает то, что вы просите.

Псевдоним должен быть включен после ключевого слова DELETE :

Вам нужно снова обратиться к псевдониму в операторе удаления, например:

Я подошел к этому несколько иначе, и у меня это сработало;

Мне нужно было удалить secure_links из моей таблицы, которая ссылалась на таблицу conditions , где больше не осталось строк условий. По сути, сценарий домашнего хозяйства. Это дало мне ошибку — вы не можете указать целевую таблицу для удаления.

В поисках вдохновения я пришел к следующему запросу, и он отлично работает. Это потому, что он создает временную таблицу sl1 , которая используется в качестве ссылки для DELETE.

Работает для меня.

Разве предложение «in» в удалении . где, крайне неэффективно, если из подзапроса будет возвращено большое количество значений? Не уверен, почему бы вам не просто внутренне (или правильно) присоединиться к исходной таблице из подзапроса по идентификатору для удаления, а не использовать «in (подзапрос)»?

И, возможно, на него ответят «MySQL не разрешает это», однако он у меня работает нормально. ПРЕДОСТАВЛЕННО. Я обязательно полностью разъясняю, что удалять (УДАЛИТЬ T ИЗ Target AS T). Удалить с соединением в MySQL проясняет проблему DELETE / JOIN.

Если вы хотите сделать это с помощью двух запросов, вы всегда можете сделать что-то подобное:

1) возьмите идентификаторы из таблицы с помощью:

Затем скопируйте результат с помощью мыши / клавиатуры или языка программирования в XXX ниже:

Возможно, вы могли бы сделать это одним запросом, но я предпочитаю это.

@CodeReaper, @BennyHill: Работает, как ожидалось.

Тем не менее, мне интересно, какова временная сложность наличия миллионов строк в таблице? По-видимому, для того, чтобы иметь 5 тыс. Записей в правильно проиндексированной таблице, потребовалось около 5ms .

Вы можете использовать псевдоним таким образом в операторе удаления

Источник

Mysql delete from не работает

Оператор DELETE удаляет из таблицы table_name строки, удовлетворяющие заданным в where_definition условиям, и возвращает число удаленных записей.

Если оператор DELETE запускается без определения WHERE , то удаляются все строки. При работе в режиме AUTOCOMMIT это будет аналогично использованию оператора TRUNCATE . See Раздел 6.4.7, «Синтаксис оператора TRUNCATE ». В MySQL 3.23 оператор DELETE без определения WHERE возвратит ноль как число удаленных записей.

Если действительно необходимо знать число удаленных записей при удалении всех строк, и если допустимы потери в скорости, то можно использовать команду DELETE в следующей форме:

Следует учитывать, что эта форма работает намного медленнее, чем DELETE FROM table_name без выражения WHERE , поскольку строки удаляются поочередно по одной.

Если указано ключевое слово LOW_PRIORITY , выполнение данной команды DELETE будет задержано до тех пор, пока другие клиенты не завершат чтение этой таблицы.

Если задан параметр QUICK , то обработчик таблицы при выполнении удаления не будет объединять индексы — в некоторых случаях это может ускорить данную операцию.

В таблицах MyISAM удаленные записи сохраняются в связанном списке, а последующие операции INSERT повторно используют места, где располагались удаленные записи. Чтобы возвратить неиспользуемое пространство и уменьшить размер файлов, можно применить команду OPTIMIZE TABLE или утилиту myisamchk для реорганизации таблиц. Команда OPTIMIZE TABLE проще, но утилита myisamchk работает быстрее. See Раздел 4.5.1, «Синтаксис команды OPTIMIZE TABLE ». See Раздел 4.4.6.10, «Оптимизация таблиц».

Первый из числа приведенных в начале данного раздела многотабличный формат команды DELETE поддерживается, начиная с MySQL 4.0.0. Второй многотабличный формат поддерживается, начиная с MySQL 4.0.2.

Идея заключается в том, что удаляются только совпадающие строки из таблиц, перечисленных перед выражениями FROM или USING . Это позволяет удалять единовременно строки из нескольких таблиц, а также использовать для поиска дополнительные таблицы.

Символы .* после имен таблиц требуются только для совместимости с Access:

В предыдущем случае просто удалены совпадающие строки из таблиц t1 и t2 .

Если применяется выражение ORDER BY (доступно с версии MySQL 4.0), то строки будут удалены в указанном порядке. В действительности это выражение полезно только в сочетании с LIMIT . Например:

Читайте также:  Мы не жалуемся мы работаем

Данный оператор удалит самую старую запись (по timestamp ), в которой строка соответствует указанной в выражении WHERE .

Специфическая для MySQL опция LIMIT для команды DELETE указывает серверу максимальное количество строк, которые следует удалить до возврата управления клиенту. Эта опция может использоваться для гарантии того, что данная команда DELETE не потребует слишком много времени для выполнения. Можно просто повторять команду DELETE до тех пор, пока количество удаленных строк меньше, чем величина LIMIT .

С MySQL 4.0 вы можете указать множество таблиц в DELETE чтобы удалить записи из одной таблицы, основываясь на условии по множеству таблиц. Однако, с такой формой оператора DELETE нельзя использовать ORDER BY или LIMIT .

Источник

DELETE. Удаление записей в таблице базы данных MySQL

Команда DELETE

Если вам необходимо удалить одну, несколько или все записи в таблице базы данных, то с этим вам поможет команда DELETE .

Синтаксис запроса на удаление записи.

Будьте предельно внимательны при выполнении запросов на удаление записей! Если вы не укажите команду WHERE и последующее условие, то будут удалены все записи в таблице.

Удаление нескольких записей таблицы

Для примера удалим несколько записей из таблицы books, которая хранится в базе данных Bookstore.

Оповестим сервер MySQL о базе данных, для которой будут выполнятся запросы.

Далее выведем записи таблицы books с идентификаторами с 1 по 5.

mysql> SELECT id, title, author, price, discount FROM books WHERE id BETWEEN 1 AND 5;
+—-+————————+——————————+———+———-+
| id | title | author | price | discount |
+—-+————————+——————————+———+———-+
| 1 | Капитанская дочка | А.С.Пушкин | 151.20 | 0 |
| 2 | Мертвые души | Н.В.Гоголь | 141.00 | 0 |
| 3 | Анна Каренина | Л.Н.Толстой | 135.00 | 20 |
| 4 | Бесы | Ф.М.Достоевский | 122.00 | 0 |
| 5 | Нос | Н.В.Гоголь | 105.00 | 0 |
+—-+————————+——————————+———+———-+
5 rows in set (0.00 sec)

Допустим необходимо удалить все записи с книгами за авторством Н.В.Гоголя. Запрос на удаление и его результат будет выглядеть следующим образом.

mysql> DELETE FROM books WHERE author= ‘Н.В.Гоголь’ ;
Query OK, 2 rows affected (0.00 sec)

Удаление всех записей таблицы

Если вам нужно очистить всю таблицу от имеющихся в ней данных, то просто выполните команду DELETE без каких либо условий.

Следующая команда удалит все записи в таблице books.

Источник

Delete with Join in MySQL

Here is the script to create my tables:

In my PHP code, when deleting a client, I want to delete all projects posts:

The posts table does not have a foreign key client_id , only project_id . I want to delete the posts in projects that have the passed client_id .

This is not working right now because no posts are deleted.

14 Answers 14

You just need to specify that you want to delete the entries from the posts table:

EDIT: For more information you can see this alternative answer

Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:

In this case, table_name1 and table_name2 are the same table, so this will work:

You can even delete from both tables if you wanted to:

Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:

Or the same thing, with a slightly different (IMO friendlier) syntax:

BTW, with mysql using joins is almost always a way faster than subqueries.

You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!

I’m more used to the subquery solution to this, but I have not tried it in MySQL:

Single Table Delete:

In order to delete entries from posts table:

In order to delete entries from projects table:

In order to delete entries from clients table:

Multiple Tables Delete:

In order to delete entries from multiple tables out of the joined results you need to specify the table names after DELETE as comma separated list:

Suppose you want to delete entries from all the three tables ( posts , projects , clients ) for a particular client :

MySQL DELETE records with JOIN

You generally use INNER JOIN in the SELECT statement to select records from a table that have corresponding records in other tables. We can also use the INNER JOIN clause with the DELETE statement to delete records from a table and also the corresponding records in other tables e.g., to delete records from both T1 and T2 tables that meet a particular condition, you use the following statement:

Notice that you put table names T1 and T2 between DELETE and FROM. If you omit the T1 table, the DELETE statement only deletes records in the T2 table, and if you omit the T2 table, only records in the T1 table are deleted.

The join condition T1.key = T2.key specifies the corresponding records in the T2 table that need be deleted.

The condition in the WHERE clause specifies which records in the T1 and T2 that need to be deleted.

Читайте также:  Не работает гидроусилитель руля шевроле лачетти что может быть

Источник

Mysql delete from не работает

DELETE is a DML statement that removes rows from a table.

Single-Table Syntax

The DELETE statement deletes rows from tbl_name and returns the number of deleted rows. To check the number of deleted rows, call the ROW_COUNT() function described in Section 12.16, “Information Functions”.

Main Clauses

The conditions in the optional WHERE clause identify which rows to delete. With no WHERE clause, all rows are deleted.

where_condition is an expression that evaluates to true for each row to be deleted. It is specified as described in Section 13.2.9, “SELECT Statement”.

If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted. These clauses apply to single-table deletes, but not multi-table deletes.

Multiple-Table Syntax

Privileges

You need the DELETE privilege on a table to delete rows from it. You need only the SELECT privilege for any columns that are only read, such as those named in the WHERE clause.

Performance

When you do not need to know the number of deleted rows, the TRUNCATE TABLE statement is a faster way to empty a table than a DELETE statement with no WHERE clause. Unlike DELETE , TRUNCATE TABLE cannot be used within a transaction or if you have a lock on the table. See Section 13.1.34, “TRUNCATE TABLE Statement” and Section 13.3.5, “LOCK TABLES and UNLOCK TABLES Statements”.

The speed of delete operations may also be affected by factors discussed in Section 8.2.4.3, “Optimizing DELETE Statements”.

To ensure that a given DELETE statement does not take too much time, the MySQL-specific LIMIT row_count clause for DELETE specifies the maximum number of rows to be deleted. If the number of rows to delete is larger than the limit, repeat the DELETE statement until the number of affected rows is less than the LIMIT value.

Subqueries

You cannot delete from a table and select from the same table in a subquery.

Partitioned Table Support

DELETE supports explicit partition selection using the PARTITION clause, which takes a list of the comma-separated names of one or more partitions or subpartitions (or both) from which to select rows to be dropped. Partitions not included in the list are ignored. Given a partitioned table t with a partition named p0 , executing the statement DELETE FROM t PARTITION (p0) has the same effect on the table as executing ALTER TABLE t TRUNCATE PARTITION (p0) ; in both cases, all rows in partition p0 are dropped.

PARTITION can be used along with a WHERE condition, in which case the condition is tested only on rows in the listed partitions. For example, DELETE FROM t PARTITION (p0) WHERE c deletes rows only from partition p0 for which the condition c is true; rows in any other partitions are not checked and thus not affected by the DELETE .

The PARTITION clause can also be used in multiple-table DELETE statements. You can use up to one such option per table named in the FROM option.

For more information and examples, see Section 22.5, “Partition Selection”.

Auto-Increment Columns

If you delete the row containing the maximum value for an AUTO_INCREMENT column, the value is not reused for a MyISAM or InnoDB table. If you delete all rows in the table with DELETE FROM tbl_name (without a WHERE clause) in autocommit mode, the sequence starts over for all storage engines except InnoDB and MyISAM . There are some exceptions to this behavior for InnoDB tables, as discussed in Section 14.6.1.6, “AUTO_INCREMENT Handling in InnoDB”.

For MyISAM tables, you can specify an AUTO_INCREMENT secondary column in a multiple-column key. In this case, reuse of values deleted from the top of the sequence occurs even for MyISAM tables. See Section 3.6.9, “Using AUTO_INCREMENT”.

Modifiers

The DELETE statement supports the following modifiers:

If you specify the LOW_PRIORITY modifier, the server delays execution of the DELETE until no other clients are reading from the table. This affects only storage engines that use only table-level locking (such as MyISAM , MEMORY , and MERGE ).

For MyISAM tables, if you use the QUICK modifier, the storage engine does not merge index leaves during delete, which may speed up some kinds of delete operations.

The IGNORE modifier causes MySQL to ignore ignorable errors during the process of deleting rows. (Errors encountered during the parsing stage are processed in the usual manner.) Errors that are ignored due to the use of IGNORE are returned as warnings. For more information, see The Effect of IGNORE on Statement Execution.

Order of Deletion

If the DELETE statement includes an ORDER BY clause, rows are deleted in the order specified by the clause. This is useful primarily in conjunction with LIMIT . For example, the following statement finds rows matching the WHERE clause, sorts them by timestamp_column , and deletes the first (oldest) one:

Читайте также:  Не хочется работать это нормально

ORDER BY also helps to delete rows in an order required to avoid referential integrity violations.

InnoDB Tables

If you are deleting many rows from a large table, you may exceed the lock table size for an InnoDB table. To avoid this problem, or simply to minimize the time that the table remains locked, the following strategy (which does not use DELETE at all) might be helpful:

Select the rows not to be deleted into an empty table that has the same structure as the original table:

Use RENAME TABLE to atomically move the original table out of the way and rename the copy to the original name:

Drop the original table:

No other sessions can access the tables involved while RENAME TABLE executes, so the rename operation is not subject to concurrency problems. See Section 13.1.33, “RENAME TABLE Statement”.

MyISAM Tables

In MyISAM tables, deleted rows are maintained in a linked list and subsequent INSERT operations reuse old row positions. To reclaim unused space and reduce file sizes, use the OPTIMIZE TABLE statement or the myisamchk utility to reorganize tables. OPTIMIZE TABLE is easier to use, but myisamchk is faster. See Section 13.7.2.4, “OPTIMIZE TABLE Statement”, and Section 4.6.3, “myisamchk — MyISAM Table-Maintenance Utility”.

The QUICK modifier affects whether index leaves are merged for delete operations. DELETE QUICK is most useful for applications where index values for deleted rows are replaced by similar index values from rows inserted later. In this case, the holes left by deleted values are reused.

DELETE QUICK is not useful when deleted values lead to underfilled index blocks spanning a range of index values for which new inserts occur again. In this case, use of QUICK can lead to wasted space in the index that remains unreclaimed. Here is an example of such a scenario:

Create a table that contains an indexed AUTO_INCREMENT column.

Insert many rows into the table. Each insert results in an index value that is added to the high end of the index.

Delete a block of rows at the low end of the column range using DELETE QUICK .

In this scenario, the index blocks associated with the deleted index values become underfilled but are not merged with other index blocks due to the use of QUICK . They remain underfilled when new inserts occur, because new rows do not have index values in the deleted range. Furthermore, they remain underfilled even if you later use DELETE without QUICK , unless some of the deleted index values happen to lie in index blocks within or adjacent to the underfilled blocks. To reclaim unused index space under these circumstances, use OPTIMIZE TABLE .

If you are going to delete many rows from a table, it might be faster to use DELETE QUICK followed by OPTIMIZE TABLE . This rebuilds the index rather than performing many index block merge operations.

Multi-Table Deletes

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE . The table_references clause lists the tables involved in the join, as described in Section 13.2.9.2, “JOIN Clause”.

For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted. For the second multiple-table syntax, only matching rows from the tables listed in the FROM clause (before the USING clause) are deleted. The effect is that you can delete rows from many tables at the same time and have additional tables that are used only for searching:

These statements use all three tables when searching for rows to delete, but delete matching rows only from tables t1 and t2 .

The preceding examples use INNER JOIN , but multiple-table DELETE statements can use other types of join permitted in SELECT statements, such as LEFT JOIN . For example, to delete rows that exist in t1 that have no match in t2 , use a LEFT JOIN :

The syntax permits .* after each tbl_name for compatibility with Access .

If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly.

If you declare an alias for a table, you must use the alias when referring to the table:

Table aliases in a multiple-table DELETE should be declared only in the table_references part of the statement. Elsewhere, alias references are permitted but not alias declarations.

Источник

Оцените статью