MySQL如何用子查询创建视图?

时间:2015-10-27 03:23:56

标签: mysql select subquery

我想创建一个名为OrderSummary的视图,其中包含CUSTOMER.FirstName,CUSTOMER.LastName,INVOICE.InvoiceDate和发票总额(通过确定INVOICE_ITEM.Quantity乘以SERVICE.ServicePrice的总和来计算)。我想使用子查询来确定发票总额。谢谢你的帮助。

CREATE VIEW OrderSummaryView AS
    SELECT c.FirstName, c.LastName, i.InvoiceDate
FROM CUSTOMER c, INVOICE i, SERVICE s  
WHERE c.CustomerID = i.InvoiceID  
AND c.CustomerID = s.ServiceID; 
SELECT sum(UnitPrice) * Quantity AS InvoiceTotal
FROM        SERVICE, INVOICE_ITEM
WHERE       SERVICE.ServiceID = invoice_item.InvoiceID

1 个答案:

答案 0 :(得分:2)

您应首先使用select语句来包含连接特定语法

override func viewDidLoad() {
    super.viewDidLoad()


    let FriendProfileView: FriendProfile = self.storyboard?.instantiateViewControllerWithIdentifier("FriendsProfile") as! FriendProfile
    let FriendMusicView: FriendsMusic = self.storyboard?.instantiateViewControllerWithIdentifier("FriendMusic") as! FriendsMusic



    self.addChildViewController(FriendProfileView)
    self.scrollView.addSubview(FriendProfileView.view)
    FriendProfileView.didMoveToParentViewController(self)

    self.addChildViewController(FriendMusicView)
    self.scrollView.addSubview(FriendMusicView.view)
    FriendMusicView.didMoveToParentViewController(self)



    var FriendMusicFrame: CGRect = FriendProfileView.view.frame
    FriendMusicFrame.origin.y = self.view.frame.height
    FriendMusicView.view.frame = FriendMusicFrame



    self.scrollView.contentSize = CGSizeMake(self.view.frame.width, self.view.frame.size.height*2)



    // Do any additional setup after loading the view.
}
enter code here

然后我们可以添加您的其他子查询

SELECT c.FirstName, c.LastName, i.InvoiceDate
FROM CUSTOMER c
JOIN INVOICE i ON c.CustomerID = i.InvoiceID 
JOIN INVOICE_ITEM ii ON ii.InvoiceID = i.InvoiceID 
JOIN SERVICE s ON ii.ServiceID = s.ServiceID;

有一件事看起来有点可疑,SELECT c.FirstName, c.LastName, i.InvoiceDate, t.InvoiceTotal FROM CUSTOMER c JOIN INVOICE i ON c.CustomerID = i.InvoiceID JOIN INVOICE_ITEM ii ON ii.InvoiceID = i.InvoiceID JOIN SERVICE s ON ii.ServiceID = s.ServiceID JOIN ( SELECT SUM(UnitPrice) * Quantity AS InvoiceTotal, i.InvoiceID FROM SERVICE s JOIN INVOICE_ITEM i ON i.InvoiceID = s.ServiceID GROUP BY i.InvoiceID ) as t ON t.InvoiceID = i.InvoiceID; 你确定所有这些都是正确的pk - > fk关系?

使用子视图创建视图,您必须分两步完成

customerid = invoiceid = serviceid