Craig Hooghiem
Craig Hooghiem

Reputation: 1282

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.

Upvotes: 12

Views: 117324

Answers (2)

Tomalak
Tomalak

Reputation: 338416

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.

Upvotes: 20

Quassnoi
Quassnoi

Reputation: 425843

SELECT  e.*
FROM    (
        SELECT  DISTINCT te.ed_id
        FROM    (
                SELECT  title_id
                FROM    sales_details
                GROUP BY
                        title_id
                HAVING  SUM(qty_shipped) > 50
                ) t
        JOIN    titleditors te
        ON      te.title_id = t.title_id
        ) te
JOIN    editors e
ON      e.ed_id = te.ed_id

Upvotes: 6

Related Questions