在Inner Join中添加WHERE子句的位置?

时间:2017-01-21 11:28:58

标签: mysql sql

我有这个查询,我需要在第一个查询中添加一个where子句(WHERE order_number = 1),但它不起作用。

SELECT 
    last_name,
    first_name,
    total,
    pickup_date,
    MPU.salary,
    MTU.materials,
    OFU.otherfee
FROM
    finished AS FD
        INNER JOIN
    (SELECT 
        order_number, (SUM(salary * hours_worked)) AS 'salary'
    FROM
        manpower_used
    GROUP BY order_number) AS MPU ON FD.order_number = MPU.order_number
        INNER JOIN
    (SELECT 
        order_number, (SUM(qty * price)) AS 'materials'
    FROM
        materials_used
    GROUP BY order_number) AS MTU ON FD.order_number = MTU.order_number
        INNER JOIN
    (SELECT 
        order_number,
            (SUM(overtime_fee + stair_fee + toll_fee)) AS 'otherfee'
    FROM
        other_fees
    GROUP BY order_number) AS OFU ON FD.order_number = OFU.order_number

谢谢!

3 个答案:

答案 0 :(得分:0)

最后。

SELECT 
    last_name,
    first_name,
    total,
    pickup_date,
    MPU.salary,
    MTU.materials,
    OFU.otherfee
FROM
    finished AS FD
        INNER JOIN
    (SELECT 
        order_number, (SUM(salary * hours_worked)) AS 'salary'
    FROM
        manpower_used
    GROUP BY order_number) AS MPU ON FD.order_number = MPU.order_number
        INNER JOIN
    (SELECT 
        order_number, (SUM(qty * price)) AS 'materials'
    FROM
        materials_used
    GROUP BY order_number) AS MTU ON FD.order_number = MTU.order_number
        INNER JOIN
    (SELECT 
        order_number,
            (SUM(overtime_fee + stair_fee + toll_fee)) AS 'otherfee'
    FROM
        other_fees
    GROUP BY order_number) AS OFU ON FD.order_number = OFU.order_number
    Where FD.order_number = 1   -- here

为了比较年份和月份的日期(比如pickup_date),您可以像这样添加另一个过滤器:

AND date_format(pickup_date,'%m-%Y') = date_format(curdate(),'%m-%Y')

答案 1 :(得分:0)

在小组之前作为Where子句,如果它在未聚合的字段上,

Select [stuff]
From [tables and joins]
Where [Filter predicates]
group by [grouping expressions]

像:

Select s.storeId, count(*)
from stores s join storeproducts sp 
    on sp.storeId = s.storeId
Where s.State = 'CA'
group by s.storeId
如果它涉及聚合函数

,则在组之后按<{1}}子句

Having

像:

Select [stuff]
From [tables and joins]
group by [grouping expressions]
Having [filter predicates on aggregate expressions]

在您的情况下,外部查询中没有Select s.storeId, count(*) from stores s join storeproducts sp on sp.storeId = s.storeId group by s.storeId having count(*) > 12 ,所以最后作为group by子句

where

答案 2 :(得分:-2)

您在查询中使用了聚合函数,这就是WHERE无法工作的原因。你必须使用HAVING关键字而不是WHERE。尝试使用HAVING,我希望它对你有用。