Difference between revisions of "Combine tables"

From SQLZOO
Jump to: navigation, search
Line 20: Line 20:
 
</source>
 
</source>
 
<div>
 
<div>
<p>You can use UNION when you have two tables you want to combine
+
<p>You can use <code>UNION</code> when you have two tables you want to combine
 
but that contain different data.</p>
 
but that contain different data.</p>
<p>You will have to make the two tables agree before you can do the UNION though</p>
+
<p>You will have to make the two tables agree before you can do the <code>UNION</code> though</p>
 
<p>In this example a staff table and a student table are combined</p>
 
<p>In this example a staff table and a student table are combined</p>
 
</div>
 
</div>

Revision as of 16:09, 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