單個查詢“如果找不到列值,則INSERT INTO表”

[英]Single query for “INSERT INTO table if column value not found”


How can I use a single query for inserting table when a column value is not found. eg/ i want to insert new user only when this username not found

如果找不到列值,如何使用單個查詢插入表。例如/我想只在未找到此用戶名時插入新用戶

what i doing now is issue 1 query to check for existing, then another query if no existing found. total 2 query

我現在正在做的是問題1查詢檢查現有,然后另一個查詢,如果沒有找到現有。共2個查詢

 INSERT INTO friends (memberID) SELECT 1 WHERE NOT EXISTS (SELECT memberID FROM friends WHERE memberID =  1)

3 个解决方案

#1


0  

You just need to add FROM DUAL

您只需要添加FROM DUAL

INSERT INTO friends 
            (memberid) 
SELECT 1 
FROM   dual 
WHERE  NOT EXISTS (SELECT memberid 
                   FROM   friends 
                   WHERE  memberid = 1)

sql fiddle

#2


0  

How about this:

這個怎么樣:

INSERT INTO YourTable (UserName)
SELECT x
FROM (SELECT 'New User Name' AS x) a
      WHERE x NOT IN(SELECT UserName
                     FROM YourTable)

#3


0  

Since you only want one row with a given value you should enforce that with a UNIQUE constraint on the table, for example:

由於您只需要一個具有給定值的行,因此您應該在表上使用UNIQUE約束強制執行該操作,例如:

ALTER TABLE friends ADD UNIQUE (memberID);

After you do that, you can simply add the IGNORE keyword to your insert statements and it won't report an error and it won't insert a duplicate row if it already exists.

執行此操作后,您只需將IGNORE關鍵字添加到insert語句中,它就不會報告錯誤,如果已存在,則不會插入重復的行。

INSERT IGNORE INTO friends(memberID) VALUES(1);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/01/29/720924038106dfcfc02c4759b98042f6.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com