mysql支援跨表delete刪除多表記錄

2021-07-05 08:37:39 字數 2107 閱讀 1251

前幾天寫了

mysql跨表更新

的一篇總結,今天我們看下跨表刪除。 

在mysql4.0之後,mysql開始支援跨表delete。 

mysql可以在乙個sql語句中同時刪除多表記錄,也可以根據多個表之間的關係來刪除某乙個表中的記錄。 

假定我們有兩張表:product表和productprice表。前者存在product的基本資訊,後者存在product的**。 

第一種跨表刪除的方式是不用join,在delete時指定用半形逗號分隔多個表來刪除,如下sql語句: 

複製**

**如下:

delete p.*, pp.* 

from product p, productprice pp 

where p.productid = pp.productid 

and p.created < '2004-01-01' 

第二種跨表刪除的方式是使用inner join在join中指定兩表之間的關聯關係,如下sql語句: 

複製**

**如下:

delete p.*, pp.* 

from product p 

inner join productprice pp 

on p.productid = pp.productid 

where p.created < '2004-01-01' 

注意:跨表刪除不必刪除所有表的資料,上面的sql語句表會同時刪除product和productprice兩張表中的資料,但是你可以指定 delete product.*從而只刪除product表中的記錄,而不處理productprice表中的記錄。 

跨表刪除也可以使用left join,例如我們要刪除所有在productprice表中沒有記錄的product表記錄。如下sql語句: 

複製**

**如下:

delete p.* 

from product p 

left join productprice pp 

on p.productid = pp.productid 

where pp.productid is null 

跨表刪除很有用,在需要的時候就用它吧。歡迎閱讀另外一篇關於

跨表更新

的介紹文章

例項:select * from sec_offline_datapageconfig t1 

join sec_offline_datapageitem t2 on t1.configid=t2.configid 

where t1.eid=15

delete sec_offline_datapageitem,sec_offline_datapageconfig from sec_offline_datapageconfig 

join sec_offline_datapageitem on sec_offline_datapageconfig.configid=sec_offline_datapageitem.configid 

where eid=15

delete t1,t2 from sec_offline_datapageconfig t1

join sec_offline_datapageitem t2 on t1.configid=t2.configid 

where eid=15

delete t1,t2 from sec_offline_datapageconfig t1,sec_offline_datapageitem t2 where t1.configid=t2.configid and eid=15

delete from sec_offline_datapageitem where configid in (

select configid from sec_offline_datapageconfig where eid=15);

delete from sec_offline_datapageconfig where eid=15

delete t from sec_offline_datapageconfig t where eid=15

delete from sec_offline_datapageconfig t where eid=15 -- 錯誤

mysql支援跨表delete刪除多表記錄

前幾天寫了 mysql跨表更新的一篇總結,今天我們看下跨表刪除。在mysql4.0之後,mysql開始支援跨表delete。mysql可以在乙個sql語句中同時刪除多表記錄,也可以根據多個表之間的關係來刪除某乙個表中的記錄。假定我們有兩張表 product表和productprice表。前者存在pr...

mysql跨庫跨表查詢

簡單記錄 select from dysns.uchome pay record,91feile.phpcms game where uchome pay record.uid phpcms game.touserid select from dysns.uchome pay record,91fe...

MySQL 跨表查詢

select 表1列名 表2列名 from 表1 表2 where 條件 select 表1列名 表2列名 from 表1 inner join 表2 on 條件 全內連線 select 表1列名 表2列名 from 表1 left right inner join 表2 on 條件 左 右內連線 ...