我有以下有效的查询(没有“WHERE stats.dt”部分)。我得到所有用户的数据。
我的问题是,这个查询当然只会产生具有 stats.dt > $timestampnow-$maxdays_data 的用户的行。但我需要所有用户,但仅当 stats.dt 大于 tstamp-maxdays 时才需要获取他们的 SUM(upload) 或 SUM(download) 值。可以忽略其他具有 upload 和 download 值的行,其中 stats.dt 小于我需要的值。
例如,nodeid 为 2 的用户不会被选中,因为他的 dt 太小。我确实希望选择用户,但不希望使用数据或上传值(它们可以是 0)。
统计表看起来像这样
nodeid | dt | upload | download
----------------------------------------
1 | 1381699533 | 345345 | 42324234
1 | 1382899152 | 7575 | 574234
1 | 1380699533 | 764534 | 7235232
2 | 1372899152 | 71455 | 124123
我不知道从哪里开始寻找如何解决这个问题,所以也许有人可以指出我正确的方向。谢谢!
SELECT b.id, b.lastname, b.name, c.balance, a.maxdebt, b.warndata, b.warndownload, b.warnupload, b.warndebt, b.cutoffdata, b.cutoffdownload, b.cutoffupload, b.cutoffdebt, b.data, b.download, b.upload, b.warning, b.access, b.cutoffstop
FROM (
SELECT customers.id AS id, SUM(tariffs.value) AS maxdebt
FROM tariffs
LEFT JOIN assignments ON tariffs.id = assignments.tariffid
RIGHT JOIN customers ON assignments.customerid = customers.id
GROUP BY id
) a
JOIN (
SELECT customers.id AS id, UPPER(lastname) AS lastname, customers.name AS name, SUM(stats.upload+stats.download) AS data, SUM(stats.download) AS download, SUM(stats.upload) AS upload, customers.cutoffstop, warndata, warndownload, warnupload, warndebt, cutoffdata, cutoffdownload, cutoffupload, cutoffdebt, nodes.warning, nodes.access
FROM customers
LEFT JOIN nodes ON customers.id = nodes.ownerid
LEFT JOIN stats ON nodes.id = stats.nodeid
LEFT JOIN customerwarnings ON customers.id = customerwarnings.id
WHERE stats.dt > ($timestampnow-$maxdays_data)
GROUP BY id
) b ON a.id = b.id
JOIN (
SELECT customerid, SUM(cash.value) AS balance
FROM cash
GROUP BY customerid
) c ON b.id = c.customerid