I have an form, where is field called team.
<input type="text" name="team" id="team" />
I would like to inser data from that field IF that same team isn't in database yet.
Basically if user writes 'Chelsea' and that is already in database table then nothing basically happends but if it's not there yet, then it's inserted in to database table tt_clubs.
Can I check that if it's already there somehow? I'm rookie with SQL still :/
EDIT also it shouldn't matter if users writes 'chelsea' or 'Chelsea' or 'chElsea'.. all those should be same.
EDIT table structure is just, 'id' <- automatic and 'Team name'
The easy way
I believe that INSERT IGNORE would solve this problem:
INSERT IGNORE INTO tt_clubs (team) VALUES ('Chelsea');
If the name already exists in the table then the insert will simply be ignored.
Also if you have not already done so set the team field to be a unique key:
ALTER TABLE tt_clubs ADD UNIQUE(team);
Another way
Attempt to select the value first:
SELECT id
FROM tt_clubs
WHERE team LIKE 'Chelsea'
Then in PHP you can check how many rows have been returned. If there is one then don't run the insert statement otherwise insert the team name.
You can use solution like this:
Use ci collation for you table. CI means case-insensitive
Add Unique KEY on this field which is store CHELSEA.
Use Insert IGNORE INTO teams(field1) VALUES('Chelsea')
Another way:
Select row from db by this field - select id from teams where field1 = 'Chelsea'.
If row empty Insert a new row.
It totally depends on the DBMS. Oracle, doesn't have the INSERT IGNORE clause. I'd do a MERGE:
MERGE INTO my_table
USING ( SELECT 1 from dual )
ON UPPER( team_name ) = UPPER( user_input )
WHEN NOT MATCHED THEN INSERT
VALUES ( user_input )
Related
I took a look at many questions similar to mine, but I didn't get what I'm looking for, maybe you guys can help me
I have this table:
What I want to do is:
Insert a new record (regardless whether "user_id" or "course_id" are already exist or not).
BUT!, if there is a record with the same "user_id" and "course_id" and "tutorial_id", then just update "tutorial_id" and "tutorial2_id" and leave the rest as they are.
I don't want to declare column "tutorial_id" as UNIQUE, because more than a user can have the same "tutorial_id" (as you can see in the above picture).
In addition, ON DUPLICATE KEY UPDATE didn't work for me.
I'm thinking of using QUERY two times, one to select and check if record exist, and the other one whether to UPDATE or INSERT, but is that correct?
Use INSERT ... ON DUPLICATE KEY UPDATE ... syntax. For it to work.
If your user_id and course_id combination is unique you could delete the id field from your table and make those two fields a primary key.
In any other case that the id field is also needed and makes a unique combination of the three for each record then make those three fields the primary key for you table (id,user_id and course_id).
How about issuing the UPDATE first, and if no records are affected (using row_count() then INSERT? This way you only test the existence condition once.
rextester demo
update test set tutorial2_id = #tutorial2
where user_id = #user_id and course_id = #course_id and tutorial_id = #tutorial_id;
insert into test (user_id, course_id, tutorial_id, tutorial2_id)
select #user_id, #course_id, #tutorial_id, #tutorial2_id)
where row_count() = 0;
i have a contactnumber column in mysql database. In contactnumber column there are more than 20,000 entries. Now when i upload new numbers through .csv file, i dont want duplicate numbers in database.
How can i avoid duplicate numbers while inserting in database.
I initially implemented logic that checks each number in .csv file with each of the number in database.
this works but takes lot of time to upload .csv file containing 1000 numbers.
Pleae suggest how to minimize time required to upload .csv file while not uploading duplicate values.
Simply add a UNIQUE constraint to the contactnumber column:
ALTER TABLE `mytable` ADD UNIQUE (`contactnumber`);
From there you can use the IGNORE option to ignore the error you'd usually be shown when inserting a duplicate:
INSERT IGNORE INTO `mytable` VALUES ('0123456789');
Alternatively, you could use the ON DUPLICATE KEY UPDATE to do something with the dupe, as detailed in this question: MySQL - ignore insert error: duplicate entry
If your contactnumber should not be repeated then make it PRIMARY or at least a UNIQUE key. That way when a value is being inserted as a duplicate, insert will fail automatically and you won't have to check beforehand.
The way I would do it is to create a temporary table.
create table my_dateasyyyymmddhhiiss as select * from mytable where 1=0;
Do your inserts into that table.
and then query out the orphans on the between mytable and the temp table based on contactnumber
then run an inner join query between the two tables and fetch out the duplicate for your telecaller tracking.
finally drop the temporary table.
Thing that this does not address are duplicates within the supplied file (don't know if that would be an issue in this problem)
Hope this help
If you don't want to insert duplicate values in table and rather wants to keep that value in different table.
You can create trigger on table.
like this:
DELIMITER $$
CREATE TRIGGER unique_key BEFORE INSERT ON table1
FOR EACH ROW BEGIN
DECLARE c INT;
SELECT COUNT(*) INTO c FROM table1 WHERE itemid = NEW.itemid;
IF (c > 0) THEN
insert into table2 (column_name) values (NEW.itemid);
END IF;
END$$
DELIMITER ;
I would recommend this way
Alter the contactnumber column as UNIQUE KEY
Using phpmyadmin import the .csv file and check the option 'Do not abort on INSERT error' under Format-Specific Options before submitting
I am running a insert statement to insert data, but I want to check for any duplicate entries based on date and then do an entry.
All I want is if today a user enters product_name='x', 'x' is unique so that no one can enter product name x again today. But of course the next day they can.
I do not want to run a select before the insert to do the checking. Is there an alternative?
You can either use
1. Insert into... on duplicate update
2. insert.. ignore
This post will answer your question
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You can use the mysql insert into... on duplicate update syntax which will basically enter in a new row if one isn't there, or if the new row would have caused a key constraint to kick in, then it can be used to update instead.
Lets say you have the following table:
MyTable
ID | Name
1 | Fluffeh
2 | Bobby
3 | Tables
And ID is set as the primary key in the database (meaning it CANNOT have two rows with the same value in it) you would normally try to insert like this:
insert into myTable
values (1, 'Fluffster');
But this would generate an error as there is already a row with ID of 1 in it.
By using the insert on duplicate update the query now looks like this:
insert into myTable
values (1, 'Fluffster')
on duplicate key update Name='Fluffster';
Now, rather than returning an error, it updates the row with the new name instead.
Edit: You can add a unique index across two columns with the following syntax:
ALTER TABLE myTable
ADD UNIQUE INDEX (ID, `name`);
This will now let you use the syntax above to insert rows while having the same ID as other rows, but only if the name is different - or in your case, add the constraint on the varchar and date fields.
Lastly, please do add this sort of information into your question to start with, would have saved everyone a bit of time :)
Hi i'm new to php and mysql.
I'm wondering how can i use PHP to check if a table in my mysql database contains a ROW which have the specific ID and if not add the data to the table .
For example,
Table structure:(Table name : record)
ID , DATA
i have ID=123 and DATA=hello stored in a variable in the php code , how can i use php sql query to find out whether the data exist by checking using its ID in the table , if not , INSERT the ID and DATA into the table.
I hope you understand.
p/s i have connected the php script to the database
Make the ID UNIQUE:
CREATE TABLE my_table( ID INT UNSIGNED UNIQUE...
then use INSERT IGNORE:
INSERT IGNORE INTO my_table( ID, DATA ) VALUES( some_id, some_data )
IF NOT EXISTS(SELECT 1 FROM structure WHERE ID = <yourid>)
INSERT INTO structure (ID, DATA) VALUES(<yourid>, <yourdata>)
Just replace INSERT with REPLACE.
http://dev.mysql.com/doc/refman/5.5/en/replace.html
Another option:
INSERT INTO record(id, `data`) SELECT 123, 'hello'
FROM new_table WHERE NOT EXISTS (SELECT id from record where id = 123 );
If your ID is unique key, then you can directly try to insert the row. If that ID is already in the table, the database would not let you insert it and will return error. Else you have to first run a SELECT statement to see if this ID exists in your table and if not insert it.
Also this thread will help you a lot I think How to 'insert if not exists' in MySQL?
Using MySQL, I assumed there was a way to do it relationally but perhaps I'm wrong.
I have table A with userID, and table B with userID, it's set so on delete of A.userID to cascade and delete B.userID.
So I have a query (Using CI), inserting information in table A, I want to insert a row into table B with the same userID (PK, AI). Sometimes it will have values to insert in B.userID row, sometimes it will be entirely null values.
Thoughts on how to do this?
Thanks.
I would really need to see the actual query, but I believe this is what you're looking for.
When you insert data in CodeIgniter you can get the Primary Key of your insert like this.
$this->db->insert('A',$data); //insert into the table with 'userID' as PK, AI
$id_of_insert = $this->db->insert_id();
$data_for_b = array(
'field' => 'value',
...
'userID' => $id_of_insert //insert the captured PK from A and place in the FK field of B
);
$this->db->insert('B', $data_for_b);
The easiest thing to do would be to write a stored procedure to perform the insert. That could do both inserts within a transaction and accept parameters for the data to add into B as well as A. Then you query would call the stored proc instead of doing a straight insert.
There are a few things you should consider in this approach:
If your auto_increment is BIGINT it gives wrong values.
If you insert something and someone else inserted something as well before you read the value you might get the wrong id. I recommend reading the value with something different that is unique. (e.g. nickname in a user registration).