I have a table that looks like this:
Number | Name
--------+--------
123 | Robert
This is what I want to do:
If the Number is already in the database, don't insert a new record.
If the Number is not in the databse, but the name is, create a new name and insert it. So for example, if I have a record that contains 123
for Number
and Bob
for Name
, I don't want to insert it, but if I get a record that contains 456
for Number
and Robert
for name
, I would insert 456
and Robert1
. I was going to check for duplicates individually like:
SELECT * FROM Person where Number = 123;
//If number is not found
SELECT * FROM Person where Name = 'Robert';
//If name is found, add a number to it.
Is there a way I can combine the two statements?
make both number and name unique.
You can now do a insert with ON DUPLICATE
For appending a number after name i would suggest using autoincrement column instead.
There are actually two problems in your question. The first problem is to make
Number
column unique and the second one is to increment the columnName
by appending a number if it already exists.FIRST PART
Since the number is
UNIQUE
, enforce aUNIQUE
constraint on the column. It could be aPRIMARY KEY
or aUNIQUE KEY
.If the column has no
KEY
and you want to make itPRIMARY
, here is theALTER
statement:but if you only want it to be
UNIQUE
and not a primary key,SECOND PART
You can actually do it without using join.
Some details:
when the value supplied on column
Number
already exists, it will throw an error since the column is unique. I have read a comment from a deleted posts saying: "..Number is not unique, but if it does exist, I don't want to enter a record." -- it does not make any sense if you don't want to add uniqueness on the column. How will you know if the number already exists or not? Doing a little check for the existence ofNumber
feels like a little overhead for me. So my best recommendation is to enforce uniqueness.Use this query, for insert the row
[123, 'Robert']
. if you want insert other values, change123
&Robert
values in below query:NOTE: if
Robert
exists in the table, above query insertsRobert1
. ifRobert1
exists, it insertsRobert2
, and so on .I haven't worked with SQL for some time, so this may be wrong ;)
Edit: