我有两个表:table1
和table2
,两个表的结构都是; id
- day
- uniques
- pageviews
。我想创建一个包含uniques
格式的2387|1283
值的附加字段,同时在给定日期汇总uniques
和pageviews
。我有:
SELECT id,
day,
Sum(uniques) AS uniques,
Sum(pageviews) AS pageviews
FROM (SELECT *
FROM table1
WHERE ` day ` >= '2016-07-21'
AND ` day ` <= '2016-07-22'
UNION
SELECT *
FROM table2
WHERE ` day ` >= '2016-07-21'
AND ` day ` <= '2016-07-22') t1
GROUP BY ` day `
ORDER BY ` day ` ASC
但是,对于2个表中的给定天数,这只是uniques
和pageviews
的总和,但我还需要知道确切的值。假设table1中有5个,table2中有3个。此查询会返回一个“唯一”字样。值为8的字段。我还需要单独获取值5和3
任何帮助都会节省很多宝贵的时间;)
谢谢
答案 0 :(得分:0)
您的查询请求总和。也许您可以执行GROUP_CONCAT(MySQL reference),以便该列返回由分隔符分隔的各个值。样本如下:
SELECT id,
day,
SUM(uniques) AS uniques,
GROUP_CONCAT(CONCAT(uniques, ':', `tablename`) SEPARATOR '|') AS uniques_values,
SUM(pageviews) AS pageviews,
GROUP_CONCAT(CONCAT(pageviews, ':', `tablename`) SEPARATOR '|') AS pageviews_values
FROM (SELECT * , 'table1' as `tablename`
FROM table1
WHERE day >= '2016-07-21'
AND day <= '2016-07-22'
UNION
SELECT * , 'table2' as `tablename`
FROM table2
WHERE day >= '2016-07-21'
AND day <= '2016-07-22') t1
GROUP BY day
ORDER BY day ASC
希望有所帮助:)