Mysql嵌套查询,1个表,3个查询,个别结果

时间:2015-01-21 12:01:23

标签: php mysql mysqli

我有什么:

2桌

- table_benefactor ( id and benefactor names)
- table_realstate  (house adress, rent, paidrent flag)

If paidrent = 0 (unpaid)
If paidrent = 1 (paid)

我需要什么:

1个嵌套查询,返回如下结果

name | totalrent | paid | unpaid
_________________________________
Jhon | 1,000.00  |100.00| 900.00
Doe  | 2,500.00  |500.00| 2,000.00
Chris| 800.00    |0.00  | 800.00

我尝试了什么:

我尝试了很多方法,但是他们没有给我我需要的结果,他们接近但不是我需要的,这是我的疑问 - >

如果我这样做,它将完全返回我想要的但不是我需要它的方式

(SELECT table_realstate.benefactor, name, SUM(rent) totalrent 
FROM table_realstate, table_benefactor 
WHERE flag = 0 
AND table_realstate.benefactor = table_benefactor.id
GROUP BY benefactor
ORDER BY name ASC) 
UNION ALL
(SELECT table_realstate.benefactor, name, SUM(rent) unpaid 
FROM table_realstate, table_benefactor 
WHERE flag = 0 
AND table_realstate.benefactor = table_benefactor.id 
AND table_realstate.paidrent = 0
GROUP BY benefactor
ORDER BY name ASC) 
UNION ALL
(SELECT table_realstate.benefactor, name, SUM(rent) paid 
FROM table_realstate, table_benefactor 
WHERE flag = 0 AND table_realstate.benefactor = table_benefactor.id 
AND table_realstate.paidrent = 1
GROUP BY benefactor
ORDER BY name ASC)

结果:

name | totalrent 
_________________
Jhon | 1,000.00  
Doe  | 2,500.00  
Chris| 800.00    
Jhon | 100.00  
Doe  | 500.00 
Jhon | 900.00 
Doe  | 2,000.00 
Chris| 800.00   

所以我一直在尝试这样的事情:

如果我这样做,结果的结构就是我需要的,但数学和恩人的名字出错了 - >

SELECT table_benefactor.name, SUM(rent) totalrent, SUM(rent) unpaid, SUM(rent) paid
    FROM table_realstate, table_benefactor,
    (SELECT table_realstate.benefactor, name, SUM(rent) totalrent 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 
    AND table_realstate.benefactor = table_benefactor.id 
    UNION ALL
    SELECT table_realstate.benefactor, name, SUM(rent) unpaid 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 
    AND table_realstate.benefactor = table_benefactor.id 
    AND table_realstate.paidrent = 0 
    UNION ALL
    SELECT table_realstate.benefactor, name, SUM(rent) paid 
    FROM table_realstate, table_benefactor 
    WHERE flag = 0 AND table_realstate.benefactor = table_benefactor.id 
    AND table_realstate.paidrent = 1) abc 
GROUP BY table_realstate.benefactor

结果:

name | totalrent | paid | unpaid
_________________________________
Jhon | 119.200   |119.200  | 119.200
Jhon | 1,800.02  |1,800.02 | 1,800.02
Jhon | 29,1964.2 |29,1964.2| 29,1964.2
Jhon | 27,000.00 |27,000.00| 27,000.00

正如你所看到的那样,恩人的名字会重演,价值就会到处都是。

我已经尝试了其他的东西,但是不想再发帖了。

1 个答案:

答案 0 :(得分:0)

我认为你只想要条件聚合。如果paidrent标志仅采用值0和1,如代码所示,那么这很简单:

select b.name, sum(re.rent) as total_rent,
       sum(re.rent * re.paidrent) as paid,
       sum(re.rent * (1 - re.paidrent)) as paid,
from table_benefactor b join
     table_realestate re
     on b.id = re.benefactor
group by b.id, b.name;