在mysql中關(guān)聯(lián)刪除與關(guān)聯(lián)更新我們會使用到update與delete來實現(xiàn),下面我來給大家舉例介紹mysql 多表關(guān)聯(lián)更新/刪除sql語句,希望此方法對你有幫助.
1、mysql 多表關(guān)聯(lián)delete中使用別名,tblwenhq是真實的表名,a是tblwenhq的別名,b是另一個表名,代碼如下:
DELETE a FROM tblwenhq a,b where a.id=b.id
2、使用mysql進行delete from操作時,若子查詢的 FROM 字句和更新/刪除對象使用同一張表,會出現(xiàn)錯誤.
DELETE FROM tab1 WHERE col1 = ( SELECT MAX( col1 ) FROM tab1 );
ERROR 1093 (HY000): You can’t specify target table ‘tab1′ for update in FROM clause //Vevb.com
正確用法:DELETE FROM tab1 WHERE col1 = ( SELECT MAX( col1 ) FROM tab1 as a);
表關(guān)聯(lián)Update筆記,代碼如下:UPDATE b,a SET b.public=a.public WHERE b.id=a.id
例,對單表執(zhí)行更新沒有什么好說的,無非就是update table_name set col1 = xx,col2 = yy where col = zz,主要就是where條件的設置,有時候更新某個表可能會涉及到多張數(shù)據(jù)表,例如,代碼如下:
update table_1 set score = score + 5 where uid in (select uid from table_2 where sid = 10);
其實update也可以用到left join、inner join來進行關(guān)聯(lián),可能執(zhí)行效率更高,把上面的sql替換成,join的方式如下:
update table_1 t1 inner join table_2 t2 on t1.uid = t2.uid set score = score + 5 where t2.sid = 10;
例1,MySQL多表關(guān)聯(lián)數(shù)據(jù)同時刪除
category(欄目信息表)和news(新聞數(shù)據(jù)表).
category中的id(欄目編號)字段作為該表的主鍵(primary key).唯一標識了一個欄目的信息.
news 中的id字段作為該表的主鍵(primary key),唯一標識了一個欄目的信息.
category_id(欄目編號)字段與category表的id字段相關(guān)聯(lián)。
1.SQL刪除語句,代碼如下:
delete category,news from category left join news on category.id = news.category_id
新聞熱點
疑難解答
圖片精選