Hello i'll give you guys an example of the database tables that are being a pain so i got 3 conected tables yeah trying to make a list into a database anyway i'm having trouble writing a insert query for it
vogelsoort
id|naam|idhooftoonder|
now idhoofdtoonder references to the id a connection table to sort of translate a list to a mysql database (the logic of the table will be added underneath)
hoofdtoonder
|pkey|Id|idondersoorten
now idhoofdtoonder references to a the following table its id
ondersoort
id|naam
I'm sorry for asking this also i'm not experienced enough yet in mysql
edit: the question is since i've tried with a simple insert query it overwrote existing data that i'm looking for help with an insert without overwriting existing id's and connections since (idhootoonder references to hooftonder(id) and hooftoonder idontersoorten references to ondersoort(id) but not all data in ondersoort is connected to the same vogelsoort and i need an insert query that doesn't overide existing connections
You need 3 insert-statements, one for each table.
You may use TRANSACTION to do it safely.
You need to use LAST_INSERT_ID() function (your PK fields must been auto_increment for this), docs: http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
START TRANSACTION;
INSERT INTO ondersoort (id, naam) VALUES (NULL, 'data');
INSERT INTO hoofdtoonder (pkey, Id, idondersoorten) VALUES (NULL, NULL, LAST_INSERT_ID());
INSERT INTO vogelsoort (id, naam, idhooftoonder) VALUES (NULL, 'data', LAST_INSERT_ID());
COMMIT;
Related
I created a table in MySql
CREATE TABLE newuser(id VARCHAR(10) PRIMARY KEY,sname VARCHAR(20));
When I INSERT record it works fine
INSERT INTO newuser VALUE('abc123','monika');
But sometimes I don't want to supply id in the INSERT query and sometimes I want to supply. In case I don't supply id MySql automatically generate one.
What can I do to get both below query works?
INSERT INTO newuser VALUE('abc123','monika');
INSERT INTO newuser VALUE('nikita');
'I don't understood ANYTHING' - very new then.
Firstly second insert statement is invalid please review https://dev.mysql.com/doc/refman/8.0/en/insert.html -
'If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list, SELECT statement, or TABLE statement.'
Secondly uuid is a function in which 'A UUID is designed as a number that is globally unique in space and time.' https://dev.mysql.com/doc/refman/8.0/en/insert.html
You can easily select uuid() to see what it produces.
You will need to increase the id size
If you wish to use it in an insert
insert into users values (uuid(),<sname>);
I followed this tutorial with 'INSERT IGNORE' first and 'INSERT ... ON DUPLICATE KEY UPDATE' then. But it doesn't work.
I'm using NodeJS to get some data from an API, and store these data into a mySQL database. Before storing data, I want to know if this row already exists.
The ID is AUTO_INCREMENT and I d'ont know this one. Instead of using async/await or promises in NodeJS, I wanted to treat this point with mySQL without knowing the ID.
I tried this one but it adds a new row with a new ID instead of another row already exists:
INSERT INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00') ON DUPLICATE KEY UPDATE nom='123456', date='2018-08-23', heure='10:45:00';
After that, I tested this one, same result:
INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00')
Thanks for your help!
Set a unique index for the 3 columns:
ALTER TABLE test ADD UNIQUE un_index(nom, date, heure);
Then execute:
INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00');
If the 3 values already exist, the row will not be inserted.
I am making a JAVA EE application, and in production I have to drop and generate a DB a lot of times.
And due to autoincrements nature, I cannot simply set the foreign key to another tables primary key after I repopulate the tables.
EXAMPLE:
INSERT INTO `krak`.`person` (`email`, `firstname`, `lastname`, `idaddress`) VALUES
('jonas#example.com', 'Jonas', 'Sørensen');
INSERT INTO `krak`.`phone` (`description`, `number`, `idperson`) VALUES
('Noka 3210', '203948129', '1');
When deleting and creating the person in krak schema his primary key will not be 1 when he is created the second time it will be 2 due to autoincrement.
Is there a way which i can do something like:
INSERT INTO `krak`.`phone` (`description`, `number`, `idperson`) VALUES
('Noka 3210', '203948129', 'WHERE 'krak'.'person' email = hisEmail');
I know this is a silly example, but I hope it shows you what I trying to do :)
If I understood the questions correctly, I think your question is about krak.phone table. You want to drop and recreate krak.phone table multiple times. If that's right, then I would suggest that you use a stored procedure to insert into krak.phone based on krak.person.
For example,
INSERT INTO `krak`.`phone` (`description`, `number`, `idperson`)
SELECT 'Noka 3210', '203948129', ID FROM krak.person P WHERE P.email = hisEmail;
I have 3 tables:
user, student, studentdetails
User's primary key is the foreign key for a field in table student (userid) and student's primary key is foreign key for a field in table studentdetails (studentid).
I need to insert data from one form to all 3 tables in one submit, following is the SQL script:
$sql = "
INSERT INTO `tbluser`(`username`, `password`, `roleid`, `datecreated`)
VALUES ('$email','$password', '$role', CURRENT_TIMESTAMP);
SELECT #uid := MAX(`userid`) FROM `tbluser`;
INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`,
`lastname`, `datecreated`)
VALUES ('#uid', '$scholar_no', '$first_name', '$middle_name', '$last_name',
CURRENT_TIMESTAMP);
SELECT #stuID := MAX(`studentid`) FROM `tblstudent`;
INSERT INTO `tblstudentdetails` (`studentid`,`dob`, `studenttype`, `gender`,
`religion`, `category`, `currentsuburbid`, `currentcityid`, `currentaddress1`,
`currentzipcode`, `currentstateid`, `currentcountryid`,`mobile`,`phone1`,`email1`,
`passportnum`, `permasuburbid`, `permaaddress1`, `dateofjoining`,
`admissionreferenceof`, `datecreated`, `dateupdated`)
VALUES ('#stuid', '$dob' ,'$studenttype' ,'$gender','$religion','$category',
'$currentsuburbid', ' $currentcityid', '$currentaddress1', '$currentzipcode',
'$currentstateid', '$currentcountryid', '$mobile',
'$phone1','$email1','$passportnum','$permanentsuburbid', '$permanentaddress1',
'$doj', ' $admissionreference',current_timestamp, current_timestamp);
";
I am not able to figure out the problem, the above script works in mysql (phpmyadmin) but in php it doesn't work. I understand, I need to use multi_query (??) which I am but it doesn't give any error and inserts in two tables, but doesn't in the third one. I feel it might be to do with the SELECT statement in between? At wits end here, I would greatly appreciate any help. Thanks heaps in advance.
It looks like you're trying to run multiple SQL statements separated by semicolons from mysqli. That doesn't work. You need to issue each distinct statement separately.
You can use MySQL's transactions (as long as you're using InnoDB or some other access method for your tables, and not MyISAM: MyISAM doesn't handle transactions).
You'd do that as follows:
$connection->begin_transaction();
/* issue your statements one by one */
$connection->commit();
This will cause all your inserts, etc, to become visible simultaneously.
BUT: you're trying to make use of your most recent autoincrement ID numbers. You're doing this wrong. You need to use MySQL's LAST_INSERT_ID() function in place of your
SELECT #uid := MAX(`userid`) FROM `tbluser`; /*wrong*/
pattern. This works because LAST_INSERT_ID() delivers the value of the ID from your first insert, so the second insert will use it. It's safe even if multiple programs are inserting things to the table because MySQL keeps a separate value for each program connection. It's faster than what you have because it doesn't have to look at the table, and return the value to your program before using it.
So do this and you'll get what you want.
/* do the first insert, using an autoincrementing uid column */
INSERT INTO `tbluser`(whatever, whatever, whatever)
VALUES (whatever, whatever, whatever);
/* now LAST_INSERT_ID() contains the value inserted into tbluser.uid */
/* do the second insert, using the id from the first insert into tblstudent.userid */
INSERT INTO `tblstudent` (`userid`, whatever, whatever, whatever)
VALUES (LAST_INSERT_ID(), whatever, whatever, whatever);
/* now LAST_INSERT_ID() contains the value inserted into tblstudend.studentid */
/* use that value to insert into tblstudentdetails.studentid */
INSERT INTO `tblstudentdetails` (`studentid`, whatever, whatever, whatever)
VALUES (LAST_INSERT_ID(), whatever, whatever, whatever);
I have three tables in my database. A users table, StoreA and StoreB
StoreA and StoreB both have a unique key which is the user ID value.
What I want is; When I create a user and insert them into the database, how can I Insert a row into the other two tables without too many additional queries.
I figure I can do this by inserting the user in one query,
then in another return the newly created user ID,
then in another, using said ID, create rows in StoreA and StoreB
Can I cut out the middle query?
Can I cut out the middle query?
YES
START TRANSACTION;
INSERT INTO user (id, name, other)
VALUES (null, 'John','rest of data');
INSERT INTO storeA (id, user_id, other)
VALUES (null, #user_id:= LAST_INSERT_ID(), 'rest of data');
INSERT INTO storeB (id, user_id, other)
VALUES (null, #user_id, 'rest of data');
COMMIT;
See: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
It's a good idea to do this in a transaction, you you're not stuck with just a user with no other data if something goes wrong.
It's not a DB requirement though.
Yes - there should be a function available to get the last inserted ID (assuming it's an autoincrement field) without another query. In PHP, it's mysql_insert_id(). Just call that after the first query.
YES
Q1: insert into table1 values (...);
Q2: insert into table2 values (last_insert_id(), ...);
last_insert_id is the default mysql build-in function
Most of the mysql libraries in various programming language did support return last insert id.
But You did not mention what sort of language you are using to connect to mysql.,
so cannot provide any example
I just wanted to share a php solution.
If you're using mysqli, first execute your insert query.
Then do
$db_id = $this->db->insert_id;
Why don't you use their username as the primary key instead of creating an arbitrary user_id field thats auto incremented? Their user names are unique, right?