Table: assignments
=======================
|customerid |tariffid |
=======================
| 1 | 2 |
| 2 | 2 |
| 1 | 4 |
| 3 | 4 |
=======================
Table: cash
=======================
|customerid | value |
=======================
| 1 | 2 |
| 1 | 9 |
| 1 | -15 |
| 2 | -9 |
| 2 | 2 |
| 2 | 2 |
| 2 | -9 |
| 3 | 9 |
=======================
Table: customers
=================================================
| id | lastname| name | cutoffstop | deleted |
=================================================
| 1 | Doe | John | 10 | 0 |
| 2 | Foo | Jack | 10 | 0 |
| 3 | Zoo | Jenny| 20 | 0 |
| 4 | Boo | Jane | 5 | 0 |
=================================================
Table: tariffs
================
| id | value|
================
| 1 | 0 |
| 2 | 2 |
| 3 | 0 |
| 4 | 9 |
================
我有四张桌子。我也有两个有效的查询,但我需要以某种方式合并查询。
第一个查询给了我一行 customerid(id) - lastname - name - balance[=sum(cash.value)]
SELECT customers.id AS id, UPPER(lastname) AS lastname, name, SUM(cash.value) AS balance
FROM customers
JOIN cash ON customers.id = cash.customerid
WHERE deleted = 0 AND cutoffstop < 50
GROUP BY customers.id, lastname, name
HAVING SUM(cash.value) < $limit
ORDER BY lastname, name
示例结果行第一个查询:
id lastname name balance
1 DOE John -4 (=2+9+-15)
第二个查询给了我一行 customerid(id) - maxdept [=sum(tariffs.value)]
SELECT SUM(tariffs.value) AS maxdebt, customers.id AS id
FROM tariffs
INNER JOIN assignments ON tariffs.id = assignments.tariffid
INNER JOIN customers ON assignments.customerid = customers.id
GROUP BY id
生成的第二行查询示例:
id maxdept
1 11 (=9+2)
注意:maxdept = $limit
现在,我真正想要的是一个组合查询,其中第一个查询中的 $limit 是第二个查询的结果 -> 每个 customerid 的关税总和(=maxdept)。(现在 $limit 在配置文件中静态定义。)
提前致谢!