加入两个选择查询

时间:2013-04-27 12:12:54

标签: mysql

我想加入两个选择查询,但不知道该怎么做。

第一个查询向我提供有关发票编号,客户端,黄昏和发票表中保存的金额的信息:

SELECT invoice.Eventid, invoice.Invoiceno, 
event.clientid, client.clientid, clientname, gross_amount, VAT, total, due
FROM client, invoice, event, 
WHERE event.eventid=invoice.eventid and event.clientid = client.clientid group by invoice.eventid

第二个查询是检查员工的工资

SELECT event_ma.eventid, salary.staffid, SUM( cost_hour * TIME_TO_SEC( TIMEDIFF( hours, pause ) ) ) /3600 AS costs
FROM salary
JOIN event_ma ON salary.staffid = event_ma.staffid
GROUP BY event_ma.eventid

最后,我希望了解每项活动的所有相关费用和收入。

3 个答案:

答案 0 :(得分:0)

你实际上可以这样使用:

CREATE VIEW `inv` AS
    SELECT invoice.Eventid AS inve, invoice.Invoiceno, 
    event.clientid, client.clientid, clientname, gross_amount, VAT, total, due
    FROM client, invoice, event, 
    WHERE event.eventid=invoice.eventid and event.clientid = client.clientid group by invoice.eventid

CREATE VIEW `ev` AS
    SELECT event_ma.eventid AS evee, salary.staffid, SUM( cost_hour * TIME_TO_SEC( TIMEDIFF( hours, pause ) ) ) /3600 AS costs
    FROM salary
    JOIN event_ma ON salary.staffid = event_ma.staffid
    GROUP BY event_ma.eventid

您的最终查询为:

SELECT * FROM `inv`, `ev`
    WHERE `inve` = `evee`;

或者您也可以考虑以这种方式使用MySQL JOIN

SELECT * FROM `inv`
    JOIN `ev` ON `inv`.`inve` = `ev`.`evee`;

答案 1 :(得分:0)

我理解这个问题的方法是,您可以进行第一个查询,然后加入eventID匹配的第二个查询。此外,只是指出您在第一个查询中使用连接语法 - 而不是使用:

Select table1.col, table2.col From
table1, table2
...

您应该使用:

Select table1.col, table2.col From
table1 
INNER JOIN table2 On
table1.colID = table2.colID

...

回答你的问题:

SELECT invoice.eventid, 
       invoice.invoiceno, 
       event.clientid, 
       client.clientid, 
       clientname, 
       gross_amount, 
       vat, 
       total, 
       due 
FROM   client, 
       invoice, 
       event, 
       inner 
       JOIN (SELECT event_ma.eventid, 
                    salary.staffid, 
                    Sum(cost_hour * Time_to_sec(Timediff(hours, pause))) / 3600 
                    AS 
                          costs 
             FROM   salary 
                    JOIN event_ma 
                      ON salary.staffid = event_ma.staffid 
             GROUP  BY event_ma.eventid) x 
         ON invoice.eventid = x.eventid 
WHERE  event.eventid = invoice.eventid 
       AND event.clientid = client.clientid 
GROUP  BY invoice.eventid 

答案 2 :(得分:0)

您可以编写一个将子查询作为数据源的查询:

select ...
from 
    (select ...) as q1
    inner join (select ...) as q2 on ...
...