Combine tables

From SQLZOO
Revision as of 14:37, 30 July 2012 by Connor (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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 staff VALUES (1007,Peter,Perfect,590);
INSERT INTO staff 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