从NOT IN删除ID

时间:2018-11-03 00:17:12

标签: mysql

我正在尝试编写一个查询来计算每个客户的总费用,其中一个客户在一个表中具有已注册的属性,而在另一个表中却未给它们开票,但是我不确定如何写查询的“不在”部分,因此不必引用特定的ID。

下面列出的查询是一个较大的查询的一部分,该查询用于计算总计,但我为此工作感到苦恼。

我尝试修改查询的“不在”部分,以删除对特定ID的引用,并对client_id进行分组,但这未返回任何结果。我也尝试了GROUP_CONCAT,但不确定执行是否正确。

我不确定a)我试图做的事情是否可行,或者b)是否有更好的方法去做我想完成的事情,但是我觉得我是否可以写在另一个子查询中,我会处于更好的状态,但是我无法将精力放在如何编写它甚至解决问题的另一种方法上。

SELECT 
    clients.client_id,
    clients.first_name,
    clients.last_name,
    SUM(total_charged) AS total_charged
FROM
    clients
        LEFT JOIN
            (SELECT 
                clients.client_id,
                route_property_reg.route_property_reg_id,
                route_property_reg.rate_charged AS total_charged
            FROM
                clients
                LEFT JOIN properties ON clients.client_id = properties.client_id
                LEFT JOIN route_property_reg ON properties.property_id = route_property_reg.property_id
            WHERE
                route_property_reg.route_property_reg_id NOT IN (
                    SELECT DISTINCT
                        invoice_lines.route_property_reg_id
                    FROM
                        clients
                        LEFT JOIN invoices ON clients.client_id = invoices.client_id
                        LEFT JOIN invoice_lines ON invoices.invoice_id = invoice_lines.invoice_id
                    WHERE
                        clients.client_id = 1)
             GROUP BY clients.client_id) 
             AS charged ON clients.client_id = charged.client_id
             GROUP BY clients.client_id

SQL Fiddle

另一次尝试但结果相似的小提琴:SQL Fiddle

预期/预期的输出将是:

| client_id | first_name | last_name | total_charged |
|-----------|------------|-----------|---------------|
|         1 |       John |       Doe |           200 |  - (route-properties # 1 and 4)
|         2 |       Jane |       Doe |           200 |  - (route-property #5)
|         3 |       John |     Smith |        (null) |
|         4 |       Jane |     Smith |        (null) |

1 个答案:

答案 0 :(得分:0)

经过大量的猜测和检查,以下对我有用:

process.subscribe(data=>doStuffWithData).catch(e=>performErrorHandling);