Difference between revisions of "Combine tables"

From SQLZOO
Jump to: navigation, search
(Created page with "Combine tables containing different data <div class='ht'> <div class=params>schema:scott</div> <source lang=sql class='tidy'>DROP TABLE staff; DROP TABLE student;</source> <so...")
 
Line 16: Line 16:
 
   lname VARCHAR(20),
 
   lname VARCHAR(20),
 
   gpa INTEGER );
 
   gpa INTEGER );
INSERT INTO staff VALUES (1007,Peter,Perfect,590);
+
INSERT INTO student VALUES (1007,Peter,Perfect,590);
INSERT INTO staff VALUES (1008,Donald,Dunce,220);
+
INSERT INTO student VALUES (1008,Donald,Dunce,220);
 
</source>
 
</source>
 
<div>
 
<div>

Revision as of 14:40, 30 July 2012

Combine tables containing different data

schema:scott
DROP TABLE staff;
DROP TABLE student;
 CREATE TABLE staff(
  staffid INTEGER,
  email VARCHAR(20),
  name VARCHAR(20),
  salary INTEGER );
INSERT INTO staff VALUES (0173,stan@bos.edu,Stern','Stan,99','000);
INSERT INTO staff VALUES (0101,ali@bos.edu,Aloof','Alison,30','000);
CREATE TABLE student (
  id INTEGER,
  fname VARCHAR(20),
  lname VARCHAR(20),
  gpa INTEGER );
INSERT INTO student VALUES (1007,Peter,Perfect,590);
INSERT INTO student VALUES (1008,Donald,Dunce,220);

You can use UNION when you have two tables you want to combine but that contain different data.

You will have to make the two tables agree before you can do the UNION though

In this example a staff table and a student table are combined

SELECT 'F' || staffid id, name name,
email email, salary salary, NULL gpa, 'Staff' species
FROM staff
UNION
SELECT 'S' || id id, lname || ',' || fname name,
id || '@bos.edu' email, NULL salary, gpa gpa,
'Student' species
FROM student
SELECT 'F' || staffid id, name name,
email email, salary salary, NULL gpa, 'Staff' species
FROM staff
UNION
SELECT 'S' || id id, lname || ',' || fname name,
id || '@bos.edu' email, NULL salary, gpa gpa,
'Student' species
FROM student
SELECT CONCAT('F',staffid) id, name name,
email email, salary salary, NULL gpa, 'Staff' species
FROM staff
UNION
SELECT CONCAT('S',id) id, CONCAT(lname,',',fname) name,
CONCAT(id,'@bos.edu') email, NULL salary, gpa gpa,
'Student' species
FROM student
SELECT 'F' + staffid id, name name,
email email, salary salary, NULL gpa, 'Staff' species
FROM staff
UNION
SELECT 'S' + id id, lname + ',' + fname name,
id + '@bos.edu' email, NULL salary, gpa gpa,
'Student' species
FROM student
SELECT 'F' + staffid id, name name,
email email, salary salary, NULL gpa, 'Staff' species
FROM staff
UNION
SELECT 'S' + id id, lname + ',' + fname name,
id + '@bos.edu' email, NULL salary, gpa gpa,
'Student' species
FROM student
Personal tools
Namespaces

Variants
Actions
Reference
Toolbox
Google AdSense