Delete row from two sql tables that join together

半城伤御伤魂 提交于 2020-01-06 18:07:49

问题


There are two tables:

Table1 : UserID Name Job
Table2 : BookID Book Car UserID

I load these two tables in one wpf datagrid:

da.SelectCommand = new SqlCommand("select Table1.UserID, Table1.Name, Table1.Job, Table2.Book, Table2.Car from Table1 inner join Table2 on Table1.UserID = Table2.UserID");

I want to delete one row from Table2 by DataGrid:

 SqlCommand com = new SqlCommand("delete from Table2 where BookID=@BookID)",con);

but not work,

How can I do it?


回答1:


You say "It must delete a book from a certain user not all books.". You have to know user id for which the books must be delete.

If you want to delete users books, do this:

delete from Table2 where userid in (user_id1,user_id1, etc .....); But you are large rows to delete, use bulk delete mechanism.

If you don't have user ids and have book ids, you have to do this:

Delete From Table2 where bookid in (book_id1,book_id2, etc ..); Or Delete From Table2 where bookid =? //according your development language, you set "?" parameter. I don't know C# syntaxe.




回答2:


You have to use the below way to delete the rows

DELETE FROM table2
WHERE  userid = (SELECT userid
                 FROM   table1);  



回答3:


Are you expecting something like this?

DELETE FROM B WHERE BOOKID IN (SELECT BOOKID FROM B,A WHERE B.USERID=A.USERID AND B.BOOK='ABCD'); 


来源:https://stackoverflow.com/questions/14414187/delete-row-from-two-sql-tables-that-join-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!