Одна инструкция delete автоматически может удалять строки в нескольких таблицах

I have two tables in MySQL

#messages table  : 
messageid
messagetitle 
.
.

#usersmessages table 
usersmessageid 
messageid
userid
.
.

Now if I want to delete from messages table it’s ok. But when I delete message by messageid the record still exists on usersmessage and I have to delete from this two tables at once.

I used the following query :

DELETE FROM messages LEFT JOIN usersmessages USING(messageid) WHERE messageid='1' ; 

Then I test

   DELETE FROM messages , usersmessages 
   WHERE messages.messageid = usersmessages.messageid 
   and messageid='1' ; 

But these two queries are not accomplishing this task .

asked Aug 5, 2009 at 14:01

Can’t you just separate them by a semicolon?

Delete from messages where messageid = '1';
Delete from usersmessages where messageid = '1'

OR

Just use INNER JOIN as below

DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'

Jobin

8,2822 gold badges36 silver badges54 bronze badges

answered Aug 5, 2009 at 14:05

EricEric

8,09819 gold badges101 silver badges131 bronze badges

12

DELETE a.*, b.* 
FROM messages a 
LEFT JOIN usersmessages b 
ON b.messageid = a.messageid 
WHERE a.messageid = 1

translation: delete from table messages where messageid =1, if table uersmessages has messageid = messageid of table messages, delete that row of uersmessages table.

answered Feb 26, 2011 at 10:00

angry kiwiangry kiwi

11.5k28 gold badges123 silver badges168 bronze badges

2

You should either create a FOREIGN KEY with ON DELETE CASCADE:

ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE

, or do it using two queries in a transaction:

START TRANSACTION;;

DELETE
FROM    usermessages
WHERE   messageid = 1

DELETE
FROM    messages
WHERE   messageid = 1;

COMMIT;

Transaction affects only InnoDB tables, though.

answered Aug 5, 2009 at 14:06

QuassnoiQuassnoi

426k94 gold badges626 silver badges619 bronze badges

6

no need for JOINS:

DELETE m, um FROM messages m, usersmessages um

WHERE m.messageid = 1 

AND m.messageid = um.messageid 

ekad

14.6k26 gold badges46 silver badges48 bronze badges

answered Sep 10, 2016 at 2:54

Fred YatesFred Yates

911 silver badge1 bronze badge

1

The OP is just missing the table aliases after the delete

DELETE t1, t2 
FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id 
WHERE t1.id = some_id

goneos

3292 gold badges4 silver badges17 bronze badges

answered Sep 28, 2018 at 7:19

2

You have two options:

First, do two statements inside a transaction:

BEGIN;
  DELETE FROM messages WHERE messageid = 1;
  DELETE FROM usermessages WHERE messageid = 1;
COMMIT;

Or, you could have ON DELETE CASCADE set up with a foreign key. This is the better approach.

CREATE TABLE parent (
  id INT NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE child (
  id INT, parent_id INT,
  FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
);

You can read more about ON DELETE CASCADE here.

answered Aug 5, 2009 at 14:13

Mike TrpcicMike Trpcic

25.7k8 gold badges79 silver badges117 bronze badges

0

DELETE message.*, usersmessage.* from users, usersmessage WHERE message.messageid=usersmessage.messageid AND message.messageid='1'

Spudley

169k39 gold badges238 silver badges308 bronze badges

answered Nov 5, 2013 at 15:04

johanjohan

611 silver badge1 bronze badge

Try this please

DELETE FROM messages,usersmessages

USING messages

INNER JOIN usermessages on (messages.messageid = usersmessages.messageid)

WHERE messages.messsageid='1'

answered Jul 3, 2013 at 5:32

AmitAmit

212 bronze badges

Try this..

DELETE a.*, b.*  
FROM table1 as a, table2 as b  
WHERE a.id=[Your value here] and b.id=[Your value here]

I let id as a sample column.

Glad this helps. :)

answered Oct 1, 2017 at 10:22

1

You can also use like this, to delete particular value when both the columns having 2 or many of same column name.

DELETE project , create_test  FROM project INNER JOIN create_test
WHERE project.project_name='Trail' and  create_test.project_name ='Trail' and project.uid= create_test.uid = '1';

answered Mar 9, 2018 at 12:45

VidyaVidya

732 silver badges10 bronze badges

there’s another way which is not mentioned here (I didn’t fully test it’s performance yet), you could set array for all tables -> rows you want to delete as below

// set your tables array
$array = ['table1', 'table2', 'table3'];


// loop through each table
for($i = 0; $i < count($array); $i++){

 // get each single array
 $single_array = $array[$i];

 // build your query
 $query = "DELETE FROM $single_array WHERE id = 'id'";

 // prepare the query and get the connection
 $data = con::GetCon()->prepare($query);

 // execute the action
 $data->execute();
}

then you could redirect the user to the home page.

header('LOCATION:' . $home_page);

hope this will help someone :)

Thanks

answered Feb 4, 2020 at 0:30

1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

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

Обязательно проверяйте ваши условия — ошибка может привести к нежелательным последствиям в базе данных.

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

Кинга Идем в IT: пошаговый план для смены профессии

Полный набор инструментов для удаления из нескольких таблиц

Использование соединений и псевдонимов таблиц

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

Применение USING для упрощения соединений

С ключевым словом USING запросы становятся проще и легче в чтении.

Умное использование ограничений внешних ключей

Ограничения внешних ключей помогают реализовать автоматическую очистку при помощи ON DELETE CASCADE, увеличивая эффективность:

Такие настройки позволяют удалять группы записей одновременно, что похоже на процесс удаления именных персонажей в кинофильме «Мстители: Война бесконечности».

Визуализация

Удаление записей из нескольких таблиц можно сравнить с организацией флешмоба:

До начала: 🏢🏬🏦🏛️💥 <- Это таблицы с данными для удаления.
Цель: мгновенное синхронное действие.

После окончания: 🌳🌳🌳🌳 <- Данные удалены, пространство в таблицах освобождено.
Результат: один сигнал — быстрое действие — чистота и порядок. Это эффективность!

Ловушки, обходные пути и профессиональные советы

Работа с особыми случаями и спецификой синтаксиса

Используйте обратные кавычки (`) для имен, совпадающих с ключевыми словами SQL:

Поддержание ссылочной целостности

При сложной структуре связей между внешними ключами и отсутствии правила ON DELETE CASCADE используйте EXISTS, NOT EXISTS, IN, NOT IN в подзапросах для сохранения целостности данных:

Совместимость версий и обработка ошибок

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

Полезные материалы

  1. MySQL :: MySQL 8.0 Справочное руководство :: 13.2.2 Оператор DELETE – основные тонкости и детали синтаксиса оператора DELETE в MySQL.
  2. MySQL :: MySQL 5.7 Справочное руководство :: 13.2.2 Оператор DELETE – описание синтаксиса оператора DELETE в предыдущих версиях MySQL.
  3. MySQL: Оператор DELETE – детальное описание с практическими примерами применения оператора DELETE.
  4. Понимание соединений JOIN в MySQL и других реляционных базах данных — SitePoint – обзор того, как работают соединения в MySQL и других реляционных базах данных.
  5. Выставление конкретных значений в начало или конец порядка сортировки – MySQL Cookbook – глубокое погружение в особенности работы с ссылочной целостностью и ограничениями внешних ключей.

From SQL DELETE

Most database management systems allow you to create a foreign key constraint so that if you delete a row in a table, the corresponding rows the related table are also removed automatically. This ensures the integrity of the data.

AND

Answered in SO. (Must be adapted to your situation)

Can’t you just separate them by a semicolon?

Delete from messages where messageid = '1';
Delete from usersmessages where messageid = '1'

OR

Just use INNER JOIN as below

DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'

EDIT due to @NIC’s comment (and DV?):

First option: table_constraint (Transact-SQL)

ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } Specifies
what action happens to rows in the table that is altered, if those
rows have a referential relationship and the referenced row is deleted
from the parent table. The default is NO ACTION.

CASCADE Corresponding rows are deleted from the referencing table if that row is deleted from the parent table.

and an example in SO

Second option:

prepare tables

DROP TABLE IF EXISTS dbo.Student, dbo.Winner

CREATE TABLE dbo.Student 
(
    ID          INT         NOT NULL,
    name        VARCHAR(30) NOT NULL,
    class       VARCHAR(30) NOT NULL
);
CREATE TABLE dbo.Winner
(
    stID        INT         NOT NULL,
    achievement INT         NOT NULL
);
GO

INSERT INTO dbo.Student(ID, name, class)
VALUES
    (1, 'Roy', '2'),
    (2, 'James', '2'),
    (3, 'Carl', '2'),
    (4, 'Peter', '2'),
    (5, 'Alice', '2')

INSERT INTO dbo.Winner(stID, achievement)
VALUES
    (1, 1),
    (2, 1),
    (3, 3),
    (4, 5),
    (5, 5)

Deleting rows

DELETE FROM Student WHERE ID = 1;
DELETE FROM Winner WHERE stID = 1

Tested in SQL Server 13.0.1722.0
note: DROP TABLE IF EXIST may not work in older versions

enter image description here

Summary: in this tutorial, we will show you how to delete data from multiple tables by using MySQL DELETE JOIN statement.

In the previous tutorial, you learned how to delete rows of multiple tables by using:

  • A single DELETE statement on multiple tables.
  • A single DELETE statement on multiple related tables which the child table has an ON DELETE CASCADE referential action for the foreign key.

This tutorial introduces to you a more flexible way to delete data from multiple tables using INNER JOIN or LEFT JOIN clause with the DELETE statement.

MySQL DELETE JOIN with INNER JOIN

MySQL allows you to use the INNER JOIN clause in the DELETE statement to delete rows from one table that has matching rows in another table.

For example, to delete rows from both T1 and T2 tables that meet a specified condition, you use the following statement:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition;Code language: SQL (Structured Query Language) (sql)

Notice that you place table names T1 and T2 between the DELETE and FROM keywords. If you omit T1 table, the DELETE statement only deletes rows in T2 table. Similarly, if you omit T2 table, the DELETE statement will delete only rows in T1 table.

The expression T1.key = T2.key specifies the condition for matching rows between T1 andT2 tables that will be deleted.

The condition of the  WHERE clause determines rows in the T1 and T2 that will be deleted.

MySQL DELETE JOIN with INNER JOIN example

Suppose, we have two tables t1 and t2 with the following structures and data:

DROP TABLE IF EXISTS t1, t2;

CREATE TABLE t1 (
    id INT PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE t2 (
    id VARCHAR(20) PRIMARY KEY,
    ref INT NOT NULL
);

INSERT INTO t1 VALUES (1),(2),(3);

INSERT INTO t2(id,ref) VALUES('A',1),('B',2),('C',3);Code language: SQL (Structured Query Language) (sql)

The following statement deletes the row with id 1 in the t1 table and also row with ref 1 in the t2 table using DELETE...INNER JOIN statement:

DELETE t1,t2 FROM t1
        INNER JOIN
    t2 ON t2.ref = t1.id 
WHERE
    t1.id = 1;Code language: SQL (Structured Query Language) (sql)

The statement returned the following message:

2 row(s) affectedCode language: SQL (Structured Query Language) (sql)

It indicated that two rows had been deleted.

MySQL DELETE JOIN with LEFT JOIN

We often use the LEFT JOIN clause in the SELECT statement to find rows in the left table that have or don’t have matching rows in the right table.

We can also use the LEFT JOIN clause in the DELETE statement to delete rows in a table (left table) that does not have matching rows in another table (right table).

The following syntax illustrates how to use DELETE statement with LEFT JOIN clause to delete rows from T1 table that does not have corresponding rows in the T2 table:

DELETE T1 
FROM T1
        LEFT JOIN
    T2 ON T1.key = T2.key 
WHERE
    T2.key IS NULL;Code language: SQL (Structured Query Language) (sql)

Note that we only put T1 table after the DELETE keyword, not both T1 and T2 tables like we did with the INNER JOIN clause.

MySQL DELETE JOIN with LEFT JOIN example

See the following customers and orders tables in the sample database:

Customers and Orders Tables

Each customer has zero or more orders. However, each order belongs to one and only one customer.

We can use DELETE statement with LEFT JOIN clause to clean up our customer master data. The following statement removes customers who have not placed any orders:

DELETE customers 
FROM customers
        LEFT JOIN
    orders ON customers.customerNumber = orders.customerNumber 
WHERE
    orderNumber IS NULL;Code language: SQL (Structured Query Language) (sql)

We can verify the deletion by finding whether customers who do not have any orders exist using the following query:

SELECT 
    c.customerNumber, 
    c.customerName, 
    orderNumber
FROM
    customers c
        LEFT JOIN
    orders o ON c.customerNumber = o.customerNumber
WHERE
    orderNumber IS NULL;Code language: SQL (Structured Query Language) (sql)

The query returned an empty result set which is what we expected.

In this tutorial, you have learned how to use the MySQL DELETE JOIN statement to delete data from two or more tables.

Was this tutorial helpful?

Нужно удалить в 2-х таблицах строчки с Id = 80, подскажите, что не так делаю?

DELETE FROM table_1 A LEFT JOIN table_2 B ON (A.Id= B.Id) WHERE Id= '80' AND A.Type= '0'


  • Вопрос задан

  • 149 просмотров

DELETE 
    A,
    B
FROM 
    table_1 A
    LEFT JOIN table_2 B ON (A.Id= B.Id)
WHERE 
    A.Id=80

Пригласить эксперта

DELETE FROM table_1 WHERE ...; DELETE FROM table_2 WHERE ...;

Повесьте внешний ключ со свойством ON DELETE … CASCADE на нужный столбец. Тогда СУБД будет автоматически удалять связанные данные из других таблиц.

BEGIN;
	DELETE FROM table_1 WHERE ID = 80; 
	DELETE FROM table_2 WHERE ID = 80;
COMMIT;

что не так делаю?

Полагаете, что запись с указанным ID существует.

Если в table_1 такой записи нет — никаких удалений не будет, даже если во второй таблице есть такие записи.

В общем случае для решения задачи одним запросом необходим FULL JOIN. Но увы, MySQL его не поддерживает. А потому в общем случае задача нерешаема.

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Стрептомицин инструкция по применению в ветеринарии для лошадей
  • Стиральная машина занусси zws 3102 инструкция
  • Противовирусные таблетки изопринозин инструкция по применению
  • Должностная инструкция инженера 1 категории службы главного энергетика
  • Ксила инструкция по применению в ветеринарии для крс