mysql insert information from multiple rows from another table - mysql

I am using MySQL version 5.6.
I have a table event that takes two ids and a date, and a table student that contains a column id. I want to insert two ids when the name match (WHERE firstname =.., AND lastname=..,). However, I don't quite know how to take id from two rows in one insert command. Can any one help me please?
Thanks,
Paul

If you are trying to insert into a table, then you want to use insert. To get data from another table or query, you would want the insert . . . select form.
From what you say, this seems something like what you want:
insert into event(id1, id2, date)
select s1.id, s2.id, now()
from student s1 cross join
student s2
where s1.id <> s2.id and
s1.firstname = firstname and s1.lastname = lastname and
s2.firstname = firstname and s2.lastname = lastname;
It would return all pairs of students where the names match (but don't have the same id).

Related

SQL: INSERT INTO table(...) VALUES (...) with data retrieved from other tables

Thank you for passing by. I know basic SQL syntax and I can't seem to find a way to accomplish this task.
I need to create a stored procedure which inserts data from one table in another, amid retrieving data from many others. Suppose I have these tables with columns:
users
name (varchar)
sub_id (int)
dub_id (int)
tmp_users
name (varchar)
sub_name (varchar)
dub_name (varchar)
subs
id (int)
name (varchar)
dubs
id (int)
name (varchar)
Translated in pseudocode I should do something like this:
INSERT INTO users (name, sub_id, dub_id)
ALL ROWS FROM tmp_users VALUES (
name = tmp_users.name,
sub_id = SELECT id FROM subs WHERE tmp_users.sub_name = subs.name,
dub_id = SELECT id FROM dubs WHERE tmp_users.dub_name = dubs.name,
)
In wording I need to insert into users all rows from tmp_users, to keep the col tmp_users.name, but retrieve the afferent ids of all other tables based on *_name column. How should I approach this task?
It seems like you are looking for the INSERT ... SELECT syntax:
INSERT INTO users (name, sub_id, dub_id)
SELECT
tu.name,
s.id,
d.id
FROM tmp_users tu
LEFT JOIN subs s ON s.name = tu.sub_name
LEFT JOIN dubs d ON d.name = tu.dub_name
This brings all rows from tmp_users, then attempt to recover the corresponding sub_id and dub_id. For each row returned by the select, a record is inserted in users. A good thing about this syntax is that you can run the select query independently first, to see what would be inserted.

Mysql Obtaining actual value through FK when Selecting all rows

I need to select * FROM sections and get the column values for every row to fill a JTable. My problem is that my adviserId column on section table is an INT
And because I'm getting the result set of every column on every row, I cannot issue a WHERE clause. I thought of subquery but since Id is different on every row, no predetermined Id can be supplied on WHERE clause.
So If I run my stored procedure, I get just an int value for adviserId instead of the teacher's name.
I have teachers and sections table.
Teacher
id PK INT
lastName
firstName
middleName
isAdviser
status
Sections
id PK
name
adviserId FK-- REFERENCING `id` column ON teacher table
What would be the best approach? I hope you can help.
Thanks.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I've created the final stored procedure based on everyone's suggestion. (THANKS AGAIN all.)
CREATE DEFINER=`root`#`localhost` PROCEDURE `getAllSectionsInfo`()
BEGIN
SELECT
s.`name` AS `Section Name`,
s.`session` AS `Session`,
CONCAT(t.lastName,',',t.firstName,' ',t.middleName) AS Adviser,
s.yearLevel AS `Year Level`,
CONCAT(syStart,'-',syEnd) AS SchoolYear
FROM sections s
INNER JOIN
teacher t on s.adviserId = t.id;
END
Yes I also think the same, that a simple inner join will do your job. Try the below example..
create table JTable as select T.id as Tid,T.lastName,T.firstName,T.middleName,T.isAdviser,T.status,S.id as Sid,S.name,S.adviserId
from Sections as S
inner join Teachers as T on T.id = S.adviserId
You can apply left join here to make sure that you have all records of Section table either related to Teachers data or with null data.
So, now the JTable will have all the columns in that you have put on the selection list.
Below is solution for db data selection
SELECT * FROM sections s INNER JOIN teacher on s.adviserId = t.id

Selecting specific records to run query on

I am trying to select a small number of records in a somewhat large database and run some queries on them.
I am incredibly new to programming so I am pretty well lost.
What I need to do is select all records where the Registraton# column equals a certain number, and then run the query on just those results.
I can put up what the db looks like and a more detailed explanation if needed, although I think it may be something simple that I am just missing.
Filtering records in a database is done with the WHERE clause.
Example, if you wanted to get all records from a Persons table, where the FirstName = 'David"
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
Your question indicates you've figured this much out, but are just missinbg the next piece.
If you need to query within the results of the above result set to only include people with more than two children, you'd just add to your WHERE clause using the AND keyword.
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
AND
NumberOfChildren > 3
Now, there ARE some situations where you really need to use a subquery. For example:
Assuming that each person has a PersonId and each person has a FatherId that corresponds to another person's PersonId...
PersonId FirstName LastName FatherId...
1 David Stratton 0
2 Matthew Stratton 1
Select FirstName,
LastName
FROM
Person
WHERE
FatherId IN (Select PersonId
From Person
WHERE FirstName = 'David')
Would return all of the children with a Father named David. (Using the sample data, Matthew would be returned.)
http://www.w3schools.com/sql/sql_where.asp
Would this be any use to you?
SELECT * from table_name WHERE Regestration# = number
I do not know what you have done up to now, but I imagine that you have a SQL query somewhere like
SELECT col1, col2, col3
FROM table
Append a where clause
SELECT col1, col2, col3
FROM table
WHERE "Registraton#" = number
See SO question SQL standard to escape column names?.
Try this:
SELECT *
FROM tableName
WHERE RegistrationNo = 'valueHere'
I am not certain about my solution. I would propose You to use view. You create view based on needed records. Then make needed queries and then you can delete the view.
View description: A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
Example:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
For more information: http://www.w3schools.com/sql/sql_view.asp

Delete Duplicate email addresses from Table in MYSQL

I have a table with columns for ID, firstname, lastname, address, email and so on.
Is there any way to delete duplicate email addresses from the TABLE?
Additional information (from comments):
If there are two rows with the same email address one would have a normal firstname and lastname but the other would have 'Instant' in the firstname. Therefore I can distinguish between them. I just want to delete the one with first name 'instant'.
Note, some records where the firstname='Instant' will have just 1 email address. I don't want to delete just one unique email address, so I can't just delete everything where firstname='Instant'.
Please help me out.
DELETE n1 FROM customers n1, customers n2 WHERE n1.ID > n2.ID AND n1.email = n2.email
DELETE FROM table WHERE id NOT IN (SELECT MIN(id) FROM table GROUP BY email)
This keeps the lowest, first inserted id's for every email.
While MiPnamic's answer is essentially correct, it doesn't solve the problem of which record you keep and which you throw away (and how you sort out related records). The short answer is that this cannot be done programmatically.
Given a query like this:
SELECT email, MAX(ID), MAX(firstname), MAX(lastname), MAX(address)
FROM customers
makes it even worse - since you are potentially selecting a mixture of fields from the duplicate rows. You'd need to do something like:
SELECT csr2.*
FROM customers csr2
WHERE ID IN (
SELECT MAX(id)
FROM customers csr
GROUP BY email
);
To get a unique set of existing rows. Of course you still need to sort out all the lreated records (hint - that's the IDs ni customers table not returned by the query above).
I don't know if this will work in MYSQL (I haven't used it)... but you should be able to do something like the following snippets.
I'd suggest you run them in order to get a feel for if the right data is being selected. If it does work, then you probably want to create a constraint on the column.
Get all of the duplicate e-mail addresses:
SELECT
EMAILADDRESS, COUNT(1)
FROM
TABLE
GROUP BY EMAILADDRESS
HAVING COUNT(1) > 1
Then determine the ID from that gives:
SELECT
ID
FROM
TABLE
WHERE
EMAILADDRESS IN (
SELECT
EMAILADDRESS
FROM
TABLE
GROUP BY EMAILADDRESS
HAVING COUNT(1) > 1
)
Then finally, delete the rows, based on the above and other constraints:
DELETE
FROM
TABLE
WHERE
ID IN (
SELECT
ID
FROM
TABLE
WHERE
EMAILADDRESS IN (
SELECT
EMAILADDRESS
FROM
TABLE
GROUP BY EMAILADDRESS
HAVING COUNT(1) > 1
)
)
AND FIRSTNAME = 'Instant'
Duplicate the table structure
Put a Unique Key on the email of the new table (just for safe)
Do a INSERT on the new table SELECTING data from the older one GROUPING by the email address
Another way to dedeupe using forsvarir answer above but modifying it a bit. This way you can keep which ever record you choose to partition by:
BEGIN TRAN
DELETE
FROM [TABLE]
WHERE
ID IN (
SELECT a.ID
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY Email ORDER BY Email) [RowNum], ID, Email
FROM [TABLE]
WHERE Email IN
(
SELECT
Email
FROM
[TABLE]
GROUP BY Email
HAVING COUNT(1) > 1
)
) a
WHERE a.RowNum > 1
)
--COMMIT TRAN
--ROLLBACK TRAN
You can follow this MySQL query:
DELETE p1
FROM Person p1, Person p2
WHERE p1.email = p2.email
AND p1.id> p2.id;

reading data from three tables using mysql

I have to join the data from two tables.
There are three table record,address and names.Id is the primary key in record table and foreign key in address and names table.There can be multiple name records for particular record.
RECORD(id (PK),text,search)
address(address_id(PK),type,street,city, id (FK))
name(name_id(PK),name,id (FK))
I want to get the data from these three tables in a way so that i will get the only first name record for each record id,not all the name records for record id's.
insert into RECORD values (1,record1,record1search);
insert into RECORD values (2,record2,record2search);
insert into name values (1,xxx,1);
insert into name values name(2,yyy,1)
insert into name values name(3,zzz,2)
i want to retriev the values in way:
record_id,text,namename_id:
1,record1,xxx,1
2,record2,zzz,3
I want the only first name record not the second or thirrd name record for particular record.
please help.
You will need an interim query on name by the record ID to find the FIRST ID and use THAT as basis to join to the actual name table. Also, you didn't provide any sample data for your address table, but that would be done in a similar fashion as the first names query performed here. Also, would the address table be associated to a specific named person and not just the ID? Will THAT be 1:many relationship to the Record ID?
select
r.id,
r.text,
n2.name,
n2.name_id
from
Record r,
join ( select n.id, min( n.name_id ) FirstNameID
from name n
group by n.id ) FirstNames
on r.id = FirstNames.id
join name n2
on FirstNames.FirstNameID = n2.name_id
SELECT RECORD.id, RECORD.text, name.name, name.name_id
FROM RECORD
LEFT JOIN address
ON address.id = RECORD.id
LEFT JOIN name
ON name.id = RECORD.id
GROUP BY RECORD.id