萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> Mysql刪除多表及多表記錄sql語句

Mysql刪除多表及多表記錄sql語句

本文章總結了同時刪除多個數據表與同時刪除多個數據表的關系數據的方法,有需要的朋友可參考一下。

批量刪除多表

刪除所有pre_前綴的表

 代碼如下 復制代碼

SELECT   CONCAT( 'drop table ',table_name,'; ')   FROM   information_schema.tables where

information_schema.tables.TABLE_NAME LIKE 'pre_%' ;


刪除所有pre_前綴的表 並且 不刪除pre_uc前綴的表

 代碼如下 復制代碼

SELECT   CONCAT( 'drop table ',table_name,'; ')   FROM   information_schema.tables WHERE

information_schema.tables.TABLE_NAME LIKE 'pre_%' AND information_schema.tables.TABLE_NAME NOT LIKE

 'pre_uc%';將得到的結果復制下來,再重新執行


刪除多表同的數據


MySQL數據庫中,如果需要多張表同時刪除數據,應該怎麼做呢?下面就將為您介紹MySQL中多表刪除的方法,希望對您有所啟迪。

1、從數據表t1中把那些id值在數據表t2裡有匹配的記錄全刪除掉

 代碼如下 復制代碼 DELETE t1 FROM t1,t2 WHERE t1.id=t2.id 或DELETE FROM t1 USING t1,t2 WHERE t1.id=t2.id

2、從數據表t1裡在數據表t2裡沒有匹配的記錄查找出來並刪除掉

 代碼如下 復制代碼

DELETE t1 FROM t1 LEFT JOIN T2 ON t1.id=t2.id WHERE t2.id IS NULL 或

DELETE FROM t1,USING t1 LEFT JOIN T2 ON t1.id=t2.id WHERE t2.id IS NULL

3、從兩個表中找出相同記錄的數據並把兩個表中的數據都刪除掉

 代碼如下 復制代碼 DELETE t1,t2 from t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t1.id=25

注意此處的delete t1,t2 from 中的t1,t2不能是別名

如:

 代碼如下 復制代碼 delete t1,t2 from table_name as t1 left join table2_name as t2 on t1.id=t2.id where table_name.id=25

 在數據裡面執行是錯誤的(MYSQL 版本不小於5.0在5.0中是可以的)

上述語句改寫成

 代碼如下 復制代碼 delete table_name,table2_name from table_name as t1 left join table2_name as t2 on t1.id=t2.id where table_name.id=25

 在數據裡面執行是錯誤的(MYSQL 版本小於5.0在5.0中是可以的)


刪除表中多余的重復記錄,只留有rowid最小的記錄(單字段)

 代碼如下 復制代碼 Delete From 表
Where 字段1 In (Select 字段1 From 表 Group By 字段1 Having Count(字段1) > 1) And
   Rowid Not In (Select Min(Rowid) From 表 Group By 字段1 Having Count(字段1) > 1)

刪除表中多余的重復記錄,只留有rowid最小的記錄(多個字段)

 代碼如下 復制代碼 Delete From 表 a
Where (a.字段1, a.字段2) In (Select 字段1, 字段2 From 表 Group By 字段1, 字段2 Having Count(*) > 1) And
   Rowid Not In (Select Min(Rowid) From 表 Group By 字段1, 字段2 Having Count(*) > 1)

    
5.刪除多於的重復記錄(單個字段,多個字段)

 代碼如下 復制代碼 delete from table where id not in ( select min(id) from table group by name)
或者
delete from table where id not in ( select min(id) from table group by 字段1,字段2)

6.刪除多余的重復記錄(單個字段,多個字段)

 代碼如下 復制代碼 delete from table where id in ( select max(id) from table group by name having count(*)>1)
copyright © 萬盛學電腦網 all rights reserved