我的问题是:
SELECT
FROM_UNIXTIME( date_added, '%m-%d-%Y' ) AS formatted_date,
SUM( tb =1 ) AS sum_users,
SUM( tb =2 ) AS sum_links,
SUM( tb =3 ) AS sum_ads,
SUM( tb =4 ) AS sum_actions
FROM (
SELECT date_added, 1 AS tb
FROM users_list WHERE 1=1
UNION ALL
SELECT date_added, 2
FROM users_links WHERE 1=1
UNION ALL
SELECT date_served, 3
FROM ads_served WHERE 1=1
UNION ALL
SELECT date_served, 4
FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC
这是我的表格数据:
用户列表
id date_added
1 1234567890
2 1334567890
3 1434567890
用户链接
id date_added
1 1244567890
2 1354567890
3 1464567890
提供广告
id date_served revenue
1 1234567891 0.01
2 1334567892 0.02
3 1434567893 0.02
行动
id date_served
1 1234561890
2 1334562890
3 1434563890
我试图将ads-served表中格式化日期的收入作为输出查询的第6列相加。我不知道从哪里开始。如果将总和(收入)添加到union select中,则会出现“列不匹配”错误。
最佳答案
这样试试。为什么使用1=1?
SELECT
FROM_UNIXTIME( date_added, '%m-%d-%Y' ) AS formatted_date,
SUM( tb =1 ) AS sum_users,
SUM( tb =2 ) AS sum_links,
SUM( tb =3 ) AS sum_ads,
SUM( tb =4 ) AS sum_actions,
sum(total) as tot_rev
FROM (
SELECT date_added,'' as total, 1 AS tb
FROM users_list WHERE 1=1
UNION ALL
SELECT date_added,'', 2
FROM users_links WHERE 1=1
UNION ALL
SELECT date_served,revenue, 3
FROM ads_served WHERE 1=1
UNION ALL
SELECT date_served,'', 4
FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC
关于mysql - 联合选择列不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5863677/