选择汇总结果

时间:2014-01-31 18:34:17

标签: mysql sql

我有一个查询,它从另一个表执行计数,然后为结果添加一列。然后我需要根据它改变原始的选择结果,但是我被告知未知的列。

E.g。以下查询从主查询中的另一个表进行计数,结果是命名共享,我需要根据该列是否大于0来过滤主查询结果集但是我得到错误unknown column shares

select b.name, event_title, ue.event_vis, event_date, 
    (select count(*) from list_shares 
        where user_id = 63 and event_id=ue.user_event_id) as shares,
    (DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE())) as days 
FROM brains b
    join user_events ue on b.user_id=ue.user_id
where b.user_id=63 and ((ue.event_vis='Public') OR (shares>0)) 
    and MOD(DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE()) + 365, 365) <= 30 
order by days asc

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

我建议使用派生表来传递聚合值并像使用“phyiscal”表一样加入它。例如:

select
    b.name,
    ue.event_title,
    ue.event_vis,
    ue.event_date, 
    tmp.shares,
    (DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE())) as days

from
    brains b join user_events ue on b.user_id = ue.user_id
    left join (
        select
            ls.user_id,
            ls.event_id,
            count(*) as shares
        from
            list_shares ls
        group by
            ls.user_id,
            ls.event_id) tmp on b.user_id = tmp.user_id and ue.user_event_id = tmp.event_id

where
    b.user_id = 63
and
    ((ue.event_vis = 'Public') OR (tmp.shares > 0))
and 
    MOD(DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE()) + 365, 365) <= 30 

order by
    days asc

请注意“左连接”。因为你在where子句中使用了OR运算符,所以在我看来你想要获得没有共享的行。

当然你也可以在你的where子句中使用相同的subselect,但这是重复的代码,更难维护。

答案 1 :(得分:0)

您不能使用计算列在同一查询中进行过滤。尝试像

这样的东西
SELECT x.*
FROM (
    /*Your Query*/
) as x
WHERE x.shares > 0

或者你可以做类似

的事情
select b.name, event_title, ue.event_vis, event_date, 
    shares.SharesCount as shares,
    (DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE())) as days 
FROM brains b
    join user_events ue on b.user_id=ue.user_id, event_id 
    JOIN (select count(*) as [sharesCount],  from list_shares 
        where user_id = 63) as shares ON shares.event_id = ue.user_event_id
where b.user_id=63 and ((ue.event_vis='Public') OR (shares>0)) 
    and MOD(DAYOFYEAR(ue.event_date) - DAYOFYEAR(CURDATE()) + 365, 365) <= 30
    AND shares.sharesCount > 0
order by days asc