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).
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 am using PHP and MySQL.
Goal:
Insert a new row into a table with an auto-increment id column.
While inserting this new row, I would like to copy the new inserted row's auto-increment id # into another column in the same row/entry.
Upon creation, the new entry/row should have the auto-incremented id column and another column with the same number.
My biggest concern:
I need all of this to happen correctly and reliably, even while other transactions from other connections could be taking place on the server.
So Far
I know only a little about last_insert_id()... and I am afraid of being able to use this reliably for my needs...
Will I ever run into a situation where the auto-increment id # will have already incremented (due to some other insert query from another connection perhaps) and now I will not get the correct id #? (I did not quite fully understand what it means when the last_insert_id() is given to the client on a per-connection basis).
Will last_insert_id() play nice with transactions since they become undefined when the transaction is made to rollback? (If another transaction is rolled back and then I run this script immediately after, will my script return NULL for last_insert_id()?)
I do not understand mysql_insert_id(); how to use it and whether or not it will help me.
So far, I have thought about:
INSERT row with column set as last_insert_id();
INSERT row; UPDATE column with SELECT last_insert_id();
SELECT last_insert_id(); INSERT row with auto-increment column and column set as last_insert_id()+1
What happens when I insert a chosen value into the auto-increment column? Will the auto-increment generator start counting from the number I insert? What if I use a value that has been used before (but doesn't exist anymore) and there exists records with id # that come after that value?
Will table or row locking allow me to achieve my desired behavior?
What is the proper/correct way to do something like this?
"last_insert_id() is given to the client on a per-connection basis"
last_insert_id is client independent and will return the ID for the
last inserted row from that client, therefore you do not need to worry
about the case that a user on another connection transacts with the
database.
I still do not fully understand what that means...
For a basic SCENARIO:
INSERT row where id = 1;
SELECT last_insert_id(); outputs 1
Person A makes a connection to the db; SELECT last_insert_id(); outputs 1.
Person B makes a connection to the db; SELECT last_insert_id(); outputs 1?
Person A INSERT another row where id = 2;
Person A SELECT last_insert_id(); outputs 2?
Person B SELECT last_insert_id(); outputs... 1 or 2??
What happens here?
And a SCENARIO that really concerns me:
Person A makes a connection with the db;
Person A SELECT last_insert_id(); outputs 1
Person A INSERT row where id = 2;
Person A SELECT last_insert_id(); outputs 2
Person B makes a connection with the db;
Person B SELECT last_insert_id(); outputs 2
Person B INSERT row where id = 3;
Person A SELECT last_insert_id(); outputs 2??
Person B SELECT last_insert_id(); outputs 3??
In this case, Person A's last_insert_id() is one count behind.
If this is true, then I will not be able to use my #3 method.
Please correct my outputs for me wherever I may be wrong.
You should check out this article regarding MySQL last_insert_id
last_insert_id is client independent and will return the ID for the last inserted row from that client, therefore you do not need to worry about the case that a user on another connection transacts with the database.
considering you may have multiple access to your DB,
i will do:
1, just insert new row and put null into the "another column" let's call it [autoID_Copy]
2, then i can run this:
update table set autoID_Copy= autoID where autoID_Copy is null
even make it faster you may do
where timeInstered < 1 min or maybe some other filter.
hope this help.
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 )
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?
I believe the question have emerged as my irritation of doing twice as much work as I could imagine is necessary.
I accept the idea that I could be lacking experience with both MySQL and PHP to think of a simpler solution.
My issue is that I have several tables (and I'd might be adding more) and of these is a parent table, only containing two fields - an id (int) and a name identifying it.
At this moment, I have seven tables with at least 15 fields in each one. Every table has a field, containing the id which I can link to the parent table.
All of these data isn't required to be filled - you will just have to create that one entry in the parent table. For the other tables, I have separate forms.
Now, these forms are made for updating the data in the fields, which means I have to pull out the data from the table if any data is available.
What I would like to do is when I receive the data from my form, I could just use an UPDATE query in my model. But if the table I want to update doesn't have an entry for that specific id, I need to do an insert.
So, my current pseudo code is like this:
$sql = "SELECT id FROM table_x WHERE parent_id = ".$parent_id;
$res = $mysql_query($sql);
if( mysql_num_rows($res) == 1 )
{
$sql = "UPDATE table_x SET ... WHERE parent_id = ".$parent_id;
}
else
{
$sql = "INSERT INTO table_x VALUES ( ... )";
}
mysql_query($sql);
I have two do this for every table I have - can I do something different or smarter or is this just the way it has to be done? Cause this seems very inefficient to me.
Use
INSERT ... ON DUPLICATE KEY UPDATE Syntax
It will insert if record not found,
otherwise, it will update existing record,
and you can skip the check before insert - details
This assuming relation for each 7 table to the parent table is 1:1
Or use REPLACE instead of INSERT - it's an insert, but will do an DELETE and then INSERT when a unique key (such as the primary key) is violated.
in mysql you can do this:
INSERT INTO table
(
col1,
col2
) VALUES(
'val1',
'val2'
) ON DUPLICATE KEY UPDATE table SET
col2 = 'val2'
take a look at the documentation for more information
mysql_query("UPDATE table table_x ..... WHERE parent_id=".$parent_id);
if (mysql_affected_rows()==0) {
mysql_query("INSERT INTO .....");
}