insert to mysql table

what is the syntax to insert a record only if the record doesn't already exist?
say its based on a column named 'testname'
LVL 25
dgrafxAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aaron TomoskySD-WAN SimplifiedCommented:
If you have a unique index on the table that's not an autonum you can use insert ignore

Insert ignore into tablename values (col1,col2, ...)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dgrafxAuthor Commented:
the uniqueness is determined by a combo of userid and testname

i need the syntax
the code i would use on sql server is appearing to fail

what i'd normally use is something like
INSERT INTO sometbl
(x,y)
SELECT 'x','y'
WHERE NOT EXISTS (Select 1 from sometbl where x='x' and y='y')

thanks
0
Kevin CrossChief Technology OfficerCommented:
As aarontomosky indicated, MySQL has the concept of INSERT IGNORE which will do insert normally unless there is a conflict which the IGNORE specifies to skip. If the two columns are not a key, you can just do EXACTLY as you did with MS SQL in MySQL. The trick in MySQL is that when using a WHERE clause you need a table. You can use FROM DUAL like in Oracle.

INSERT INTO sometbl(x,y)
SELECT 'x','y'
FROM DUAL
WHERE NOT EXISTS (Select 1 from sometbl where x='x' and y='y')
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Aaron TomoskySD-WAN SimplifiedCommented:
You can have a unique across multiple columns. Cleaner and integrity is guaranteed. And inserts will be faster. .
0
dgrafxAuthor Commented:
ok - thanks a lot guys
i will test it later - i cant right now
0
dgrafxAuthor Commented:
thanks a lot guys
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.