我的服务器中有很多表,它们是日期的名称。例
e_20150916
,e_20150917
,e_20150918
,e_20150919
.....等
当用户在我的输入类型中添加日期时,我想做这个表......例如,当他想要2015/08/1到2015/08/15之间的总摘要时。请帮我解决这些问题。
我正在使用2个表合并。
这里是我对2个表的查询
SELECT e.cus,e.cusname,
e.gid,
SUM(total)
FROM (
SELECT
e.cus,
e.cusname,
e.gid,
ROUND(SUM(TIMEDIFF(FROM_UNIXTIME(stoptime / 1000),
FROM_UNIXTIME(starttime / 1000))) / 60, 4) as total
FROM
e_cdr_$table
WHERE e.cusname LIKE '%$customername%'
UNION ALL
SELECT
e.cus,
e.cusname,
e.gid,
ROUND(SUM(TIMEDIFF(FROM_UNIXTIME(stoptime / 1000),
FROM_UNIXTIME(starttime / 1000))) / 60, 4) as total
FROM
e_cdr_$table1
WHERE e.cusname LIKE '%$customername%'
) s
我需要对7个表进行此查询。我该怎么办?
答案 0 :(得分:0)
正如之前的评论所指出的那样,每个日期都有一个单独的表格,这不是最聪明的方法,但如果你需要和你一起生活的情况至少可以做到UNION ALL
在子查询中执行操作,然后使用单个SUM
子句执行实际选择和WHERE
- magic:
SELECT cus,cusname,gid,
ROUND(SUM(TIMEDIFF(FROM_UNIXTIME(stoptime / 1000),
FROM_UNIXTIME(starttime / 1000))) / 60, 4) as total
FROM (
SELECT * FROM e_20150916 UNION ALL
SELECT * FROM e_20150917 UNION ALL
SELECT * FROM e_20150918 UNION ALL
SELECT * FROM e_20150919 UNION ALL
SELECT * FROM e_20150920 UNION ALL
SELECT * FROM e_20150921 UNION ALL
SELECT * FROM e_20150922 ) tbls
WHERE cusname LIKE '%$customername%'
GROUP BY cus,cusname,gid
我不确定性能问题。如果结果表明您的表格过于庞大,那么您当然可以通过以下方式单独限制其范围:
SELECT cus,cusname,gid,
ROUND(SUM(TIMEDIFF(FROM_UNIXTIME(stoptime / 1000),
FROM_UNIXTIME(starttime / 1000))) / 60, 4) as total
FROM (
SELECT * FROM e_20150916 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150917 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150918 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150919 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150920 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150921 WHERE cusname LIKE '%$customername%' UNION ALL
SELECT * FROM e_20150922 WHERE cusname LIKE '%$customername%') tbls
GROUP BY cus,cusname,gid