联合选择列不匹配

时间:2011-05-02 23:45:32

标签: mysql select union

这是我的疑问:

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

这是我的表数据:

users_list

id    date_added
1     1234567890
2     1334567890
3     1434567890

users_links

id    date_added
1     1244567890
2     1354567890
3     1464567890

ads_served

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表格中formatted_date的收入作为输出查询的第6列。我迷失在哪里开始。如果我将总和(收入)添加到联合选择中,则会出现“列不匹配”错误。

2 个答案:

答案 0 :(得分:3)

revenue属于ads_served,但您要从不存在revenue的子查询中进行选择。将其添加到子查询:

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( revenue ) As sum_revenue
FROM (
    SELECT date_added, 1 AS tb, 0 As revenue
        FROM users_list WHERE 1=1
    UNION ALL 
    SELECT date_added, 2, 0
        FROM users_links WHERE 1=1
    UNION ALL 
    SELECT date_served, 3, revenue
        FROM ads_served WHERE 1=1
    UNION ALL 
    SELECT date_served, 4, 0
        FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC

答案 1 :(得分:1)

尝试这种方式。你为什么用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