Multiple tables in one view?

青春壹個敷衍的年華 提交于 2020-01-02 08:12:23

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/6038447/multiple-tables-in-one-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!