Multiple tables in one view?

Today my question is: how can I create a view in a MySQL database that uses more than two tables?

Here is my request (it works) I do not want to change my current request, basically looking for a good link 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`

Thank you for your time!

+3
source share
1 answer

To use more than two tables, you just keep adding instructions JOINfor connecting foreign keys. Adapting your code to add an imaginary third table tbl_productsmight 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

, . table1->table2 table2->table3, FROM WHERE. , , , , .

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
+6

All Articles