Inserting data to table - mysql

currently I have three table: test, contact and staff
test
FirstName LastName
Contact
Contact_Id Contact_FirstName Contact_LastName
staff
Staff_ID Contact_Id
The Staff Id should be auto-increment, I need a script that go through all row in test table. If the FirstName and LastName Matches Contact_FirstName and Contact_LastName. Add Matched Contact_ID number to the Contact_Id thats in the Staff table.

INSERT INTO `staff` (`Contact_Id`)
SELECT c.`ContactId`
FROM `Contact` c
JOIN `Test` t ON c.`Contact_FirstName` = t.`FirstName` AND
c.`Contact_LastName` = t.`LastName`

First change the structure of Staff table by adding IDENTITY in CREATE statement if you want it to be auto-incremented.
CREATE TABLE Staff (StaffID INT IDENTITY, ContactID INT)
now try this to insert just contactID because IDENTITY allows you to skip that column, sql creates those IDs for you.
INSERT Staff SELECT Contact_ID FROM Contact c JOIN Test t ON c.Contact_FirstName=t.FirstName and c.Contact_LastName=t.LastName
this seems like it's checking contact names of Contact based on Contact names of Test.. but this should work if you pass name of person in place of t.FirstName and t.LastName

Related

Merging rows and updating related foreign key

I have a current users table. A distinct user is defined as when the email and phoneNumber together are unique. Currently the table looks like this:
And another table called giftee_info which has the foreign key on column userId to users.id:
The users table is going to be parsed out into 2 tables: users and user_metadata. Now a distinct user will be defined by the phoneNumber. So you can see in the data above, users with id's 4 and 5 are the same, and have to be merged.
The new users table will look like:
And the new user_metadata table will look like this:
Note how the 4th row has userId of 4, so users 4 and 5 have merged to one user.
And giftee_info will look like this:
See how the 3rd row in giftee_info contains userId 4, as the user with id 5 has been merged into one user.
The data I've provided is basic. In reality there are many rows, and a user with the same number may have 5 different email address (and so are currently treated as separate users in the current schema).
The part I'm having most trouble with is updating giftee_info. So any rows with userId's that have been merged down into one user need to be updated. How can I do this?
Since phonenumber can be NULL, I'm using externalid as the unique identifier below.
Start by creating the new users table from the distinct phone numbers in the old users table:
CREATE TABLE new_users (id INT PRIMARY KEY AUTO_INCREMENT, externalid VARCHAR(32), phonenumber VARCHAR(32))
SELECT DISTINCT NULL, externalid, phonenumber
FROM users
Then put all the emails into the user_metadata table, by joining the old and new users tables to get the emails along with the new user IDs.
CREATE TABLE user_metadata (id INT PRIMARY KEY AUTO_INCREMENT, userid INT, email VARCHAR(100), subscribe INT(1))
SELECT NULL, nu.id, u.email, 0
FROM new_users as nu
JOIN users AS u ON nu.externalid = u.externalid
Now you can update giftee_info by replacing the old user IDs with the new user IDs.
UPDATE giftee_info AS g
JOIN users as u ON g.userid = u.userid
JOIN new_users As nu ON nu.externalid = u.externalid
SET g.userid = nu.userid
Once this is all done you can rename the tables so new_users is now users.

MySQL Delete-Select row

I'm trying to delete a row from table subscription where there is two foreign Keys (id_user and id_journal). The information that I have is email from table user and nome from table journal. The deleted row needs to match user.email and journal.nome. I can't find a solution. How can I do it?
Table user:
id
name
email
password
Table journal:
id
name
Table Subscription:
id
id_user
id_journal
The last two queries that I tried:
DELETE FROM assinatura WHERE (
SELECT tbluser.id, journal.id
FROM tbluser, journal
WHERE email = '$email' AND nome = '$nome')
DELETE FROM assinatura
INNER JOIN tbluser on (tbluser.email = '$email')
INNER JOIN journal on (journal.nome = '$nome')
I've tried many others queries, but unsuccessful. I think it's important to say that I'm new at MySQL.
DELETE
FROM Subscription
WHERE id_user IN (
SELECT usr.id
FROM user AS usr
WHERE usr.email = INPUT_EMAIL
)
AND id_journal IN (
SELECT jrnl.id
FROM journal AS jrnl
WHERE jrnl.name = INPUT_NAME
)
On another topic ...
Try to avoid excess subscriptions for same user/journal combo by
CREATE TABLE subscription
(
id int NOT NULL AUTO_INCREMENT primary key,
id_user int not null,
id_journal int not null,
UNIQUE KEY `user_journal_intersect` (`id_user`,`id_journal`)
-- note Alan stated FK RI in place already
);
U can PK on composite instead, of course (ditching the id column), programmer pref

SQL insert one record with multiple relational data in one transaction

Say, I have a customer profile with many contacts. That means I will have separated contact table from customer table.
tbl_customer
CustomerId (PK, NOT NULL, UNIQUE, AUTO_INCREMENT)
CustomerName
Address
(etc)
tbl_contact
ContactId (PK, NOT NULL, UNIQUE, AUTO_INCREMENT)
CustomerId (FK REFERENCES tbl_customer(CustomerId), CONSTRAINT)
Contact Type
Contact Number
So now let say, a customer called John Leweinsky has 4 contacts.
ContactType1: Fax
ContactType2: Office Phone
ContactType3: Personal Phone
ContactType4: Personal Phone
Can this be done in one query transaction without knowing CustomerId?
Thanks for advance if you have answered this.
Try like this
START TRANSACTION;
insert into (feilds name) values(Values);
insert into tbl_contact(CustomerId ,ContactType,ContacNumber)
values((select max(CustomerId) from tbl_customer),'type1','Fax');
COMMIT;
Pass all other contacttype
Assuming the name is unique, you can do this as:
insert into tbl_contact(CustomerId, ContactType, ContactNumber)
select cust.CustomerId, c.ContactType, c.ContactNumber
from (select 'Fax' as ContactType, Faxnumber as ContactNumber union all
select 'Office', Officenumber union all
select 'PersonalPhone', PersonalPhone union all
select 'PersonalPhone', PersonalPhone
) c cross join
Customers cust
where cust.CustomerName = 'John Leweinsky';
If name is not unique, you need some way to disambiguate the customers.
No, the only way to properly add something to tbl_contact is with the CustomerId. You're Customer Name is not unique ( nor should it be ) so you have no way to link your contacts with John Leweinsky, unless this is just a toy example and you want to pretend that John Leweinsky is unique.
You can add the contacts without knowing the CustomerId ( in some database engines, PostgreSQL for exapmle ) but the won't be connected to John Leweinsky.

Normalize contacts in MySQL database

I am trying to create a chat application with a login. I am using MySQL database for storing the user data. My table is called userData. It contains:
userID*
userPass
firstname
surname
role
contacts
OK, so this system is for staff and students and users are able to add contacts to their list. I am struggling to structure my database to store the contacts efficiently. Basically I am not sure how to normalize with the contacts column.
For example...
userID* userPass firstname surname role contacts
1234 2012 Sponge Bob Student 1345
1234 2012 Sponge Bob Student 3421
1234 2012 Sponge Bob Student 1445
Would it be appropriate for me to create a table for each userID to store the contacts? I am making this in JAVA using a MySQL db. Would be grateful for any tips.
You should have two tables, one with user data and other with contacts. This can then be joined by using the shared identifier.
CREATE TABLE userData (userID int primary key, userPass varchar(32), firstname varchar(32), surname varchar(32), roleID int);
CREATE TABLE roles (roleID int primary key, rolename char(32));
CREATE TABLE contacts (userID int, contactID int);
I threw 'roles' in there as an example. You can then join these as necessary, e.g:
SELECT contacts.* FROM contacts
JOIN userData USING (userID)
WHERE userData.userID=1234;
Or to take if further and benefit from the normalization:
SELECT CONCAT(ud.firstName,' ',ud.surName),
CONCAT(cd.firstName,' ',cd.surName)
FROM contacts
JOIN userData AS cd on (cd.userID=contacts.contactID)
JOIN userData AS ud on (ud.userID=contacts.userID)
WHERE
contacts.userID=1234;

create two tables linked with foreign key, insert,delete,and update in mysql

i have a scenario, in which i have to create a table with following fields
department_name, ministry_name, domain_name, coordinator_name, coordinator_email
now, for each department_name there can be more than one coordinator_name and corresponding to it more than one coordinator_email.
i can't do this in one table(department) because i can't store two coordinator name and their coordinator email in a single row of mysql.
so i planned to make one table(coordinator) with department_name(primary key), ministry_name, domain_name
and second table with department_name(primary key), coordinator_name, coordinator_email with a foreign key reference to department(department_name)
now how can i use insert statement so that the data gets inserted in both tables at once. and similarly how can i use delete and update statement...
please help... thankyou...
You could use one table
Department A - Ministry - Domain - Coordinator A - Coordinator E-mail A
Department A - Ministry - Domain - Coordinator B - Coordinator E-mail B
Department A - Ministry - Domain - Coordinator C - Coordinator E-mail C
Department B - Ministry - Domain - Coordinator A - Coordinator E-mail A
If you just need Departments, you disregard coordinators' information and group it by department? Unless you specifically want two tables?
You could use TRIGGERS to achieve that, trigger will happen every time INSERT, UPDATE, DELETE is executed.
Split it in two different tables
Coordinator: id, name, email, departmentId (Foreign Key to Departments.id)
Departments: id, name, ministry, domain
Then Foreign key will take care of updates and deletions (will remove all coordinators if department is deleted)
-- edit
Then first you loop through departments:
SELECT DISTINCT(department_name) FROM your_table
and if then second loop is to display all coordinators for each department
SELECT * FROM your_table WHERE department_name = ''
Just unclear about your question. You wrote that table Coordinator will have department_name as primary key. How is this possible? Shouldnt you have department_name as foriegn key in Coordinator table? I am sorry if i misinterpreted your question
First off, don't use names for a primary key, use an id as the key instead. Take your department, make an id (auto increment) and no value so that it does this itself. Then generate a unique id that is attached to that department name, then you can use this unique id to call up later if needed. However, you will need this id to associate the other names with this department. Keep the department name in one table that you created the unique id with, and have another table that has these names with this id for each of the values used. And you need more than one query to do this.
dept. table: id(primary|auto inc) uid dept_name
coord. table: id(primary|auto inc) uid(from dept. table) min_name coord_name coord_email
<?php
mysql_query("
insert into `dept` values(
NULL,
`$uid`,
`$dept_name`
)
");
mysql_query("
insert into `coord` values (
NULL,
`$uid`,
`$coord_name`,
`$coord_email`,
`$ministry_name`
)
");
?>
Maybe this solved it for you.
if you use 2 tables
Table "Department"
Columns : id, name, ministry, domain
Table "Coordinator"
Columns : id, name, email, departmentId
Assuming you relation between Department and Coordinator table. Below query should return records based on department name
select * from Coordinator
join Department on Coordinator.departmentId = Department.Id
Where Department.name = '' --- pass any name you want in single quotes
Let me know if this works for you