今天我的问题是如何在使用两个以上表的MySQL数据库中创建视图?
这是我的查询(它有效)我不打算改变我当前的查询,主要是寻找一个很好的参考,并提供有关此主题的示例。
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`
谢谢你的时间!
答案 0 :(得分:6)
要使用两个以上的表,只需继续添加JOIN
语句即可连接外键。调整代码以添加虚构的第三个表tbl_products
可能如下所示:
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
相关联。以下只是为了说明而没有多大意义,因为您可能在同一个表中没有客户ID作为产品价格。
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