MySql - 创建视图以从多个表中读取

时间:2014-10-30 14:05:00

标签: mysql

我已经存档了一些旧订单项,这些订单项不再是最新但仍需要引用它们的发票。我想我需要创建一个VIEW但不能真正理解它。有人可以提供帮助,以便我可以运行查询来提取发票,然后提取所有已分配的订单项的总数(无论项目在哪个表中)?

CREATE TABLE `Invoice` (
  `Invoice_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `Invoice_CreatedDateTime` DATETIME DEFAULT NULL,
  `Invoice_Status` ENUM('Paid','Sent','Unsent','Hold') DEFAULT NULL,
  `LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  KEY `LastUpdatedAt` (`LastUpdatedAt`)
) ENGINE=MYISAM DEFAULT CHARSET=latin1

CREATE TABLE `Invoice_LineItem` (
  `LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
  `LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
  `LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
  `LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`LineItem_ID`),
  KEY `LastUpdatedAt` (`LastUpdatedAt`),
  KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

CREATE TABLE `Invoice_LineItem_Archived` (
  `LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
  `LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
  `LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
  `LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`LineItem_ID`),
  KEY `LastUpdatedAt` (`LastUpdatedAt`),
  KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MYISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

通常我会运行以下查询来获取发票上应付的金额

SELECT
    Invoice_ID,
    Invoice_CreatedDateTime,
    Invoice_Status,
    (SELECT SUM(LineItem_Amount) AS totAmt FROM Invoice_LineItem WHERE LineItem_InvoiceID=Invoice_ID) AS Invoice_Total
FROM
    Invoice
WHERE
    Invoice_Status='Sent'

另外,如何在一个查询中选择两个表中的所有订单项?

SELECT
    LineItem_ID,
    LineItem_ChargeType,
    LineItem_Amount
FROM
    Invoice_LineItem
WHERE
    LineItem_InvoiceID='1234'

2 个答案:

答案 0 :(得分:2)

您可以使用MERGE Storage Engine创建一个虚拟表,该表是两个真实表的并集:

CREATE TABLE Invoice_LineItem_All 
(
  `LineItem_ID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `LineItem_ChargeType` VARCHAR(64) NOT NULL DEFAULT '',
  `LineItem_InvoiceID` INT(11) UNSIGNED DEFAULT NULL,
  `LineItem_Amount` DECIMAL(11,4) DEFAULT NULL,
  `LastUpdatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY (`LineItem_ID`),
  KEY `LastUpdatedAt` (`LastUpdatedAt`),
  KEY `LineItem_InvoiceID` (`LineItem_InvoiceID`)
) ENGINE=MERGE UNION=(Invoice_LineItem_Archived, Invoice_LineItem);

答案 1 :(得分:0)

您可以使用UNION

SELECT a.* FROM a 
  UNION
SELECT b.* FROM b;

您只需要在不同的查询中使用相同数量和类型的列。 据我记忆,您可以在子查询中添加测试,但我不确定您是否可以对全局结果进行排序。

http://dev.mysql.com/doc/refman/4.1/en/union.html