从多个表中选择时选择总和

时间:2017-06-14 09:06:36

标签: mysql

我正在尝试选择一些值,我使用了以下查询:

SELECT 
    l.*,SUM(lp.amount) AS landPayMonth,p.pName,u.uName,SUM(ci.amount) AS totAmnt,
    t.unitId
FROM
    (SELECT DISTINCT landlord_payment.id,landlord_payment.amount,landlord_payment.landlordId FROM landlord_payment) lp,
    (SELECT DISTINCT cashIn.id,cashIn.tenantId,cashIn.registeredTime,cashIn.amount FROM cashIn) ci,landlords l,properties p,units u,tenants t
WHERE
    ci.tenantId = t.id
        AND l.id = lp.landlordId
        AND t.unitId = u.id
        AND u.propertyId = p.id
        AND p.landlordId = l.id
        AND STR_TO_DATE(ci.registeredTime, '%Y-%m') = STR_TO_DATE(CURDATE(), '%Y-%m')
GROUP BY l.id;

运行上述查询后得到的结果的一部分是:

id  fName  lName     landPayMonth pName           uName   totAmnt   unitId  
1   Kigen  Chemweno  100000       Smart Apartments Hse 21 32200     1

landPayMonth和totAmnt会产生错误的结果。其他一切都还可以。 某些表的某些部分如下: Cashin的

    tenantId    amount  registeredTime  
        2        8000   2017-06-02 17:48:34
        1        20100  2017-05-10 10:04:46
        1        100    2017-06-08 10:31:02
        2        6000   2017-06-05 14:34:13
        2        2000   2017-06-07 14:15:30

地主

id  fName   lName
1   Kigen   Chemweno
3   Samwel  Ekiru

属性

id  pName             landlordId
1   Smart Apartments    1
2   Iten Star           3

租户

id  fName       lName    unitId
1   Florence    Cheptum     1
2   Rose        Boit        2

单位

id  uName   propertyId
1   Hse 21  1
2   Hse 20  1

landlord_payment

id  landlordId  amount
1   1           20000
3   1           5000

我不知道自己做错了什么

0 个答案:

没有答案