How can I insert my data into two different tables in MySQL? - mysql

Hi I'm new in using MySQL, I would like to insert my data into two different tables, I don't know how to do it using a query. All I know from now is how to insert multiple data in one table.
My input Data in 5 textboxes were
textbox1 = Garcia (to be inserted in table1)
textbox2 = Michael (to be inserted in table1)
textbox3 = David (to be inserted in table1)
textbox4 = 24 (to be inserted in table2)
textbox5 = 8888888 (to be inserted in table2)
My table fields looks like this
Table1
Last Name
First Name
Middle NAme
Table2
Age
Contact No.

Since you've not specified a UI language I'm assuming that you simply want the SQL commands to do this.
INSERT INTO Table1 (`Last Name`, `First Name`,`Middle NAme`)
VALUES ("Garcia","Michael", "David");
INSERT INTO Table2 (`Age`, `Contact No.`)
VALUES (24, 8888888);
You've used bad table field names though. If this isn't working it is because you should remove periods and spaces from them all.
Also, it looks like you are just playing around but if you were being serious you'd want to include all of this information in one table and give that table a good name and an ID field.

I agree with with first answer you can have as many insert statement as you need if you are using SQL Server you need to add the word go between statements

Related

Importing sql file data omitting columns (MySql)

I am building a new booking system in PHP at the moment and I want to take over most of the data of the old system (MySQL) however the database structure of the new system will be slightly different. However I think I could take over some of the tables. Is it possible to import rows of old tables to the new table given that the column names are equal but some column names in the new table might be missing?
an example, the old table:
tourguides
id name address email telephone_mobile telephone_home
the new table
tourguides
id name address telephone_mobile
the new table doesn't has the column telephone_home, this shouldnt stop the import but instead it should be ignored
Yes, it's possible.
You should do an INSERT SELECT with fixed fields, like this:
INSERT INTO table1 (fieldX, fieldY) SELECT fieldX, fieldY FROM table2
You can even do it between databases:
INSERT INTO db1.table1 (fieldX, fieldY) SELECT fieldX, fieldY FROM db2.table2

Inserting Persons with IDs in one query?

I need to add data to a MySQL database like that:
Person:
pId, nameId, titleId, age
Name:
nameId, name
Title:
titleId, title
I don't want to have any names or title more then once in the db so I didn't see a solution with LAST_INSERT_ID()
My approach looks like that:
INSERT IGNORE INTO Name(name) VALUES ("Peter");
INSERT IGNORE INTO Title(title) VALUES ("Astronaut");
INSERT INTO Person(nameId, titleId, age) VALUES ((SELECT nameId FROM Name WHERE name = "Peter"), (SELECT nameId FROM Name WHERE name = "Astronaut"), 33);
But I guess that's a quite dirty approach!?
If possible I want to add multiple persons with one query and without having anything more then one times in db.
Is this possible in a nice way? Thanks!
You could put title and name as two columns of your table and then:
set one UNIQUE index on each column if you don"t want to have two titles or two names identical in the DB
or set an UNIQUE index on (title,name) if you don't want to have two entries having both the same name and the same title.
If you really want to have separate tables, you could do as you suggested in your post, but wrapping all your insert statements in a TRANSACTION to allow rollback if you detect a duplicate somewhere.
See Design dilemma: If e-mail address already used, send e-mail "e-mail address already registered", but can't because can't add duplicate to table which appear to be exactly the same problem, but having name & email instead of name & titles.
START TRANSACTION;
INSERT INTO title(value) VALUES ("Prof.");
SELECT LAST_INSERT_ID() INTO #title_id;
-- Instead of using user-defined variable,
-- you should be able to use the last_insert_id
-- equivalent from the host language MySQL driver.
INSERT INTO username(value) VALUES ("Sylvain");
SELECT LAST_INSERT_ID() INTO #username_id;
-- Instead of using user-defined variable,
-- you should be able to use the last_insert_id
-- equivalent from the host language MySQL driver.
INSERT INTO account(username_id, email_id) VALUES (#username_id,#title_id);
COMMIT;
See LAST_INSERT_ID()
A third solution would be to SELECT before doing you insert to see in the entry are already present. But personally I wouldn't push to the check-before-set approach at the very least, this will require an extra query which is mostly superfluous if you use correctly indexes.

Using a trigger to alter an existing row when a row with a duplicate key is added in MySQL

I have a table called jobs in a MySQL database.
One user adds data by importing an Excel file into a linked table in Access.
This works fine, except occasionally, there is a row with a duplicate id.
What I would like to do when this happens is take the data from one column (comments) of the new row and insert it into the existing row with the identical id.
For example, the original table:
id customer product comments
1 Jeff Widget Hello
2 Fred Sprocket Important comment here
Some imported data:
id customer product comments
2 Fred A new and different comment
3 Jerry Widget More comments
The table after importing the above data:
id customer product comments
1 Jeff Widget Hello
2 Fred Sprocket A new and different comment
3 Jerry Widget More comments
I'm at a loss as to how to build a trigger that would achieve this goal.
Any advice?
EDIT: Opted to use a PHP script to clean up the duplicates after the fact. Thanks for the input, all.
From my experience with Access linked tables, this can only be done with code or a two-step query process. First inserting the new records, and then performing an update operation with the remainder of the data set (you could do it in the opposite order as well). Is this something you need to do on an ongoing basis, or just a one time deal?
I think this may be of help.
As I understand it, you run an and INSERT statement and tell MySQL what to UPDATE when a duplicate key is inserted.
So, your table insert statement would look something like this:
INSERT INTO mysqlTable (id,customer,product,comment)
SELECT id,customer,product,comment FROM linkedTable
WHERE x = y
ON DUPLICATE KEY UPDATE comment = linkedTable.comment;
I would suggest using REPLACE INTO. But also, you have to be careful with REPLACE INTO as it actually deletes the previous entry and starts a new row.
http://dev.mysql.com/doc/refman/5.0/en/replace.html
I did this recently using mssql. I ran an update first. After that I ran the insert on what was left. I have never worked with access and quite frankly don't want to.
update table1 set comments = (select comments from table2 where table2.id = table1.id) where table1.id in (select table2.id from table2);
insert into table1 (customer,product,comments) select customer, product, comments from table2 where table2.id not in (select table1.id from table1);
Not sure if you can do joins on the insert and update like you can in mssql/t-sql
Hope it helps

Inserting database row with values from another table

Basically, I have two tables: images and servers. When I want to insert a row into the images table, I need to specify a s_id as one of the fields. Problem is, I only have name, which is another field in the servers table. I need to find what s_id belongs to name, and then use that in my INSERT INTO query on the images table.
Maybe this image will help:
http://i.imgur.com/rYXbW.png
I only know the name field from the servers table, and I need to use it to get the s_id field from the servers table. When I have that, I can use it in my INSERT INTO query, as it's a foreign key.
I found this:
http://www.1keydata.com/sql/sqlinsert.html
But it just confused me even more.
One solution would be to run two queries. One to get the s_id, and one to run the insert query. But I'd like to limit the amount of queries I run if there's a reasonable alternative.
Thanks!
You can use the INSERT ... SELECT form, something like this (with real column names and values of course):
INSERT INTO images (s_id, u_id, name, filename, uploaded)
SELECT s_id, ...
FROM servers
WHERE name = 'the name'
I don't know where you're getting the u_id, name, filename, or uploaded column values for images but you can include them as literal values in the SELECT:
INSERT INTO images (s_id, u_id, name, filename, uploaded)
SELECT s_id, 11, 'pancakes', 'pancakes.jpg', '2011-05-28 11:23:42'
FROM servers
WHERE name = 'the name'
This sort of thing will insert multiple values if servers.name is not unique.
You should be able to do something like this, but you'll need to fill in the items in <> with the values you want to insert.
INSERT INTO images (s_id, u_id, name, filename, uploaded)
(SELECT s_id, <u_id>, <name>, <filename>, <uploaded>
FROM imgstore.servers
WHERE name = #server_name)
This is the syntax for SQL Server, but I think it will work with MySQL as well.
Here's an article on INSERT ... SELECT Syntax
Please see my comment above regarding a potential data integrity issue. I am assuming that the name field in your server table has a unique constraint placed on it.
There are a couple of ways that you can approach this INSERT, and I'm sure that some are better than others. I make no claim that my way is the best way, but it should work. I don't know how you're writing this query, so I'm going to use #FieldValue to represent the variable input. My approach is to use a subquery in your insert statement to get the data that you require.
INSERT INTO images (field1, field2... s_id) VALUES ('#field1val', '#field2val'... (SELECT s_id FROM servers WHERE name='#nameval'));

Fix DB duplicate entries (MySQL bug)

I'm using MySQL 4.1. Some tables have duplicates entries that go against the constraints.
When I try to group rows, MySQL doesn't recognise the rows as being similar.
Example:
Table A has a column "Name" with the Unique proprety.
The table contains one row with the name 'Hach?' and one row with the same name but a square at the end instead of the '?' (which I can't reproduce in this textfield)
A "Group by" on these 2 rows return 2 separate rows
This cause several problems including the fact that I can't export and reimport the database. On reimporting an error mentions that a Insert has failed because it violates a constraint.
In theory I could try to import, wait for the first error, fix the import script and the original DB, and repeat. In pratice, that would take forever.
Is there a way to list all the anomalies or force the database to recheck constraints (and list all the values/rows that go against them) ?
I can supply the .MYD file if it can be helpful.
To list all the anomalies:
SELECT name, count(*) FROM TableA GROUP BY name HAVING count(*) > 1;
There are a few ways to tackle deleting the dups and your path will depend heavily on the number of dups you have.
See this SO question for ways of removing those from your table.
Here is the solution I provided there:
-- Setup for example
create table people (fname varchar(10), lname varchar(10));
insert into people values ('Bob', 'Newhart');
insert into people values ('Bob', 'Newhart');
insert into people values ('Bill', 'Cosby');
insert into people values ('Jim', 'Gaffigan');
insert into people values ('Jim', 'Gaffigan');
insert into people values ('Adam', 'Sandler');
-- Show table with duplicates
select * from people;
-- Create table with one version of each duplicate record
create table dups as
select distinct fname, lname, count(*)
from people group by fname, lname
having count(*) > 1;
-- Delete all matching duplicate records
delete people from people inner join dups
on people.fname = dups.fname AND
people.lname = dups.lname;
-- Insert single record of each dup back into table
insert into people select fname, lname from dups;
-- Show Fixed table
select * from people;
Create a new table, select all rows and group by the unique key (in the example column name) and insert in the new table.
To find out what is that character, do the following query:
SELECT HEX(Name) FROM TableName WHERE Name LIKE 'Hach%'
You will se the ascii code of that 'square'.
If that character is 'x', you could update like this:(but if that column is Unique you will have some errors)
UPDATE TableName SET Name=TRIM(TRAILING 'x' FROM Name);
I'll assume this is a MySQL 4.1 random bug. Somes values are just changing on their own for no particular reason even if they violates some MySQL constraints. MySQL is simply ignoring those violations.
To solve my problem, I will write a prog that tries to resinsert every line of data in the same table (to be precise : another table with the same caracteristics) and log every instance of failures.
I will leave the incident open for a while in case someone gets the same problem and someone else finds a more practical solution.