kstev
kstev

Reputation: 740

Multiple tables in one view?

Today my question is how would I go about creating a view in a MySQL database that uses more than two tables?

Here is my query (it works) I am not looking to change my current query, mostly looking for a nice reference with examples on this topic.

CREATE OR REPLACE VIEW vw_itemsPurchased AS
SELECT `tbl_buyers`.`fldPrimaryKey` as fldFKeyBuyer, `tbl_buyers`.`fldEmail` as fldBuyerEmail, `tbl_buyers`.`fldAddressStreet`, `tbl_buyers`.`fldAddressCity`, `tbl_buyers`.`fldAddressState`, `tbl_buyers`.`fldAddressZip`, `tbl_buyers`.`fldAddressCountry`, `fldPaymentCurrency`, `fldPaymentGross`, `fldPaymentStatus`, `fldReceiverEmail`, `fldTransactionId`
FROM `tbl_transactions` INNER JOIN `tbl_buyers`
ON `tbl_transactions`.`fldFKeyBuyer` = `tbl_buyers`.`fldPrimaryKey`

Thanks for your time!

Upvotes: 3

Views: 14720

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

To use more than two tables, you simply continue adding JOIN statements to connect foreign keys. Adapting your code to add an imaginary third table tbl_products might look like this:

CREATE OR REPLACE VIEW vw_itemsPurchased AS (
  SELECT 
   tbl_buyers.fldPrimaryKey as fldFKeyBuyer, 
   tbl_buyers.fldEmail as fldBuyerEmail, 
   tbl_buyers.fldAddressStreet, 
   tbl_buyers.fldAddressCity, 
   tbl_buyers.fldAddressState, 
   tbl_buyers.fldAddressZip, 
   tbl_buyers.fldAddressCountry, 
   fldPaymentCurrency, fldPaymentGross, 
   fldPaymentStatus, 
   fldReceiverEmail,
   fldTransactionId,
   tbl_tproducts.prodid
 FROM 
   tbl_transactions 
    INNER JOIN tbl_buyers ON tbl_transactions.fldFKeyBuyer = tbl_buyers.fldP
    -- Just add more JOINs like the first one..
    JOIN tbl_products ON tbl_products.prodid = tbl_transactions.prodid

In the above method, the first and second tables relate, and the first and third tables relate. If you have to relate table1->table2 and table2->table3, list multiple tables in the FROM and relate them in the WHERE. The below is just for illustration and doesn't make much sense, as you probably wouldn't have a customer id in the same table as a product price.

SELECT
  t1.productid,
  t2.price,
  t3.custid
FROM t1, t2, t3
WHERE 
  -- Relationships are defined here...
  t1.productid = t2.productid 
  AND t2.custid = t3.custid

Upvotes: 6

Related Questions