Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to join a view with a table?

UPDATED:

I am using MySQL statement to create a view:

I need to show Editors First Name, Last Name and the City if they shipped more than 50 books. The three tables I have are:

create table editors (
 ed_id  char(11),
 ed_lname varchar(20),
  ed_fname varchar(20),
  ed_pos  varchar(12),
  phone  varchar(10),
  address  varchar(30),
  city  varchar(20),
  state  char(2),
  zip  char(5),
  ed_boss  char(11));

create table titleditors (
 ed_id  char(11),
 title_id char(6),
 ed_ord  integer);

create table salesdetails (
 sonum  integer,
 qty_ordered integer,
 qty_shipped integer,
 title_id char(6),
 date_shipped date);

Can anyone tell me what code would be to create this result? I didn't make the tables, I just have to work with what I was given.

like image 263
Craig Hooghiem Avatar asked Apr 08 '10 14:04

Craig Hooghiem


1 Answers

Antiquated syntax (note the intermixing of join conditions and filter conditions):

CREATE VIEW qtyorderedview AS
  SELECT 
     salesdetails.title_id, salesdetails.qty_shipped,
     editors.ed_id, editors.ed_lname, editors.ed_fname, editors.city
  FROM
     titleditors, salesdetails, editors 
  WHERE
     titleditors.title_id = salesdetails.title_id
     AND editors.ed_id = titleditors.ed_id
     AND salesdetails.qty_ordered > 50

Modern syntax (join conditions and filter conditions are separate):

CREATE VIEW qtyorderedview AS
  SELECT 
     salesdetails.title_id, salesdetails.qty_shipped,
     editors.ed_id, editors.ed_lname, editors.ed_fname, editors.city
  FROM
     titleditors
     INNER JOIN salesdetails ON titleditors.title_id = salesdetails.title_id
     INNER JOIN editors      ON editors.ed_id = titleditors.ed_id
  WHERE
     salesdetails.qty_ordered > 50

Joins against views work exactly like joins against tables. Just use the view name in place of a regular table name.

like image 96
Tomalak Avatar answered Oct 04 '22 03:10

Tomalak