By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,471 Members | 711 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,471 IT Pros & Developers. It's quick & easy.

using subquery with insert to avoid duplicate records

P: 2
Hello,

I am trying to use a subquery to avoid duplicate entries when someone submits a form to subscribe to a mailing list.

So I want to check if the email exists before adding the record.

I tried something like:
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO mailing_list (ID,Email) VALUES ('','$Email') WHERE NOT EXISTS (SELECT * FROM mailing_list  WHERE Email LIKE '$Email'')
Using NOT IN and various other structures, but keep receiving mysql errors.

I can just "give up" and run two queries, the first to look for the email and the second to enter the email if it does not already exist; I just want to start being more efficient and using subqueries. Thanks for any advice!!!
Aug 20 '07 #1
Share this Question
Share on Google+
3 Replies


pbmods
Expert 5K+
P: 5,821
Heya, Audj.

Try this:
Expand|Select|Wrap|Line Numbers
  1. REPLACE
  2.     INTO
  3.         `mailing_list`
  4.         (
  5.             `Email`
  6.         )
  7.     VALUES
  8.         (
  9.             '$Email'
  10.         )
  11.  
For best results, make sure `Email` is a unique key.
Aug 20 '07 #2

P: 2
Ah, that's a good approach. I often forget REPLACE.

Still gotta tackle those subqueries though...

Thanks...

Audj!
Aug 20 '07 #3

pbmods
Expert 5K+
P: 5,821
Heya, Audj.

Glad to hear you got it working! Good luck with your project, and if you ever need anything, post back anytime :)
Aug 20 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.