SQL generate foreign key id from foreign tables varchar? - mysql

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;

Related

Error "#1062 - Duplicate entry '' for key 'PRIMARY'" in phpmyadmin when trying to INSERT INTO an empty table

I have 2 tables in the same DB in phpmyadmin. Table 'csv' is where I imported data in order to clean it and format it. 'client' is a table/back-end connected to my forms UI. I am trying to INSERT selected columns from 'csv' INTO 'client'. I have checked that they are both in MyISAM format. And I am not including any PK columns. The 'client' table has a PK column that is generated by my front-end code. But I cleared that table of any test data so there can't be any duplicates.
Here is the sql I'm using:
INSERT INTO client
(`first_name`, `last_name`, `street_address`, `city`, `zipcode`, `cell`)
SELECT `CSVFirst` as `first_name`,`CSVLast` as `last_name`, `CSVAddress` as `street_address`, `CSVCity` as `city`, `CSVZip` as `zipcode`, `CSVPhone` as `cell`
FROM csv
any help is greatly appreciated.
It turns out I needed an UPDATE not an INSERT. The Duplicate key message was because when INSERTing, it tries to add rows after the last existing row. which all have NULL pk values, hence the duplictae. So to add rows into an existing set of rows, use UPDATE:
UPDATE table2
JOIN table1 ON
table2.first_name= table1.table1First
AND table2.street_address = table1.table1Address
AND table2.cell = table1.table1Phone
SET day = table1day WHERE 1
Try INSERT IGNORE INTO read more about it here https://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm#:~:text=Use%20the%20INSERT%20IGNORE%20command,silently%20without%20generating%20an%20error.

MYSQL innerjoin insert Multiple tables

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;

Insert to table or update if exists using MYSQL database

I have mysql database. I need to update country list on my table. there is some country in my table. I need to check that country if not exist and insert to the table. I'm used following sql script. But this is not working. when execute this code it will duplicate the record.
MySQL Query:
INSERT INTO `moneyexpressstore`.`countries` (`Name`, `Code`, `CurrencyId`) VALUES
('Australia', 'au', NULL) ON DUPLICATE KEY UPDATE Name=VALUES(Name)
thanks,
First make sure your database does not have duplicate records on column countries, then execute this
CREATE UNIQUE INDEX countriesindex ON countries (Name(50))
50 is the amount of characters that the index will search for "unique" values. For example if that number was 3, then these two different string would be considered the same, and a 1062 Duplicate Entry error would occur abcHELLO=abcWORLD and in your case it would force the UPDATE instead of INSERT.
If you get a 1062 error, that means you have duplicates in your db so find them remove them and try again.
After this your query will execute just fine and will update instead of duplicate on "Name"
Have a look in the documentation of mysql https://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Try this:
insert into `moneyexpressstore`.`countries` (id, `Name`, `Code`, `CurrencyId`) values(NULL,'Australia', 'au', NULL) on duplicate key update name=values(name)
Please refer this link:
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

Multiple insert in multiple tables if nonindexed field not exists

I have a task to update existing multiple product-related tables with new entries if product name doesn't exist (no update). Thing is that this is one time action so product name column is not and will not be set as unique, primary, etc (and it is not possible for me to change it anyway).
I would be delighted if i could access the database remotely and use PHP, but due to security reasons i have access only to PhpMyAdmin on that server.
After googling for couple of hours i realized that either all results are about single INSERT IGNORE or similar constructions, or they are too complicated for me non-mysql brain to understand or solutions just won't work (like IF statement throws syntax error on that 5.5.8 MySQL server.
So thing is - there are 7 tables with all kinds of information on product (product, variant, image, category, product relation to category, prices, discounts). I have to check if product name doesn't exist and if true then insert new entries in all 7 tables. Additionaly i should create new product category entry if such doesn't exist (again, by name, not id)
In my humble opinion it would be like this:
IF (SELECT ProductName from `product` where ProductName='Pony') IS NULL THEN
INSERT INTO `product` VALUES ('', 'Pony');
#productId = (SELECT LAST_INSERT_ID());
INSERT INTO `category` (Name) SELECT 'Everything Nice' FROM `category` WHERE NOT EXISTS (SELECT Name FROM `category` WHERE Name='Everything Nice') LIMIT 1;
SET #categoryId = (SELECT CategoryId FROM `category` WHERE Name='Everything Nice');
INSERT INTO `product_rel_category` VALUES (#productId, #categoryId);
INSERT INTO `variant` VALUES ('', 'Nice');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Sweet');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Pink');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
... etc ...
ENDIF;
MySQL yells about syntax on IF in such query. I also tried working all kinds of procedures, but since I know only 'insert, update, select, delete', there is nothing much i can compose now.
So do you have an advise on solution on how i can make multiple INSERT/SELECT queries if a value in one table doesn't exist.
Sincerely thanks.

MySQL How to insert new record or update a field depending on whether it exists?

I am trying to implement a rating system where I keep the following two fields in my db table:
rating (the current rating)
num_rates (the number of ratings submitted so far)
UPDATE `mytable`
SET rating=((rating*num_rates)+$theRating)/num_rates, num_rates=num_rates+1
WHERE uniqueCol='$uniqueCol'
the variables are from my PHP code.
So, basically sometimes the row with the uniqueCol does not exist in the DB, so how can I do the above statement if the exists and if it doesn't then do something like this:
INSERT INTO `mytable`
SET rating=$theRating, num_rates=1, uniqueCol=$uniqueCol
Have a look at INSERT ... ON DUPLICATE KEY UPDATE.
It should look something like that:
INSERT INTO mytable (rating, num_rates, uniqueCol)
VALUES ($theRating, 1, $uniqueCol)
ON DUPLICATE KEY UPDATE
rating=((rating*num_rates)+$theRating)/num_rates,
num_rates=num_rates+1;
Make sure to have a UNIQUE index or PRIMARY KEY on your uniqueCol.