开发者

SQL INSERT or UPDATE

开发者 https://www.devze.com 2023-01-10 12:34 出处:网络
Following on from this: SQL INSERT from SELECT and the correct answer marked there. I will need to be able to also check whether the row already exists, also by using the username. So would I delete

Following on from this: SQL INSERT from SELECT and the correct answer marked there.

I will need to be able to also check whether the row already exists, also by using the username. So would I delete and then insert or is there a better way? And if it is delete, how do I say DELETE FROM开发者_如何学运维 table WHERE UserID = do the username select here Thanks


If delete then you can use:

DELETE a FROM Avatar a LEFT JOIN User u ON a.UserID=u.UserID WHERE u.UserName='theusername'


Try REPLACE INTO instead of INSERT INTO. If the UserID is specified and is the primary key for the table, this will overwrite the row whose UserID matches what you insert.

To answer your sub-question, it would be DELETE FROM table WHERE UserID IN (SELECT UserID ...)

Side note: StackOverflow is really not an appropriate venue for learning basic SQL. If you read up first, your questions will be better and the answers correspondingly more useful.


Coming from the other question where you're doing an "insert from select", I assume you want to not insert the row that already have entries for the keys you're attempting to insert. I also assume that it's giving you some error like "duplicate key found".

With those assumptions in mine, the fix is simple: add the IGNORE keyword after INSERT, so you're query looks something like this:

INSERT IGNORE... //rest of query
0

精彩评论

暂无评论...
验证码 换一张
取 消