协助MySQL查询 - 省略,分组?

时间:2011-11-10 09:56:02

标签: mysql

对日志db进行一些调查并编写查询。

我加入了许多表来恢复我需要的数据,但我想稍微清理一下。

该查询返回所有用户以及他们在其帐户中启用的功能。

以下是我要做的清理工作:

他们是一个名为'actions'的专栏,有两个状态,'添加'和'删除'

如果用户功能具有“已删除”操作,那么我希望不显示该用户的同一功能的任何行,这些行也标记为“已添加”

这可能吗?!

这是我到目前为止所做的:

select users.id as site_id, users.company_name, feature_log.featurecode, feature.minimum_account as feature_type, users.account_type as site_type, account_types.name as account, feature_log.action, feature_log.time
from users
inner join
    feature_log
    on users.id = feature_log.siteid
inner join 
    feature
    on feature_log.featurecode = feature.featurecode
inner join account_types
    on users.account_type_INC = account_types.id
where feature.minimum_account != 0
    AND feature.minimum_account > users.account_type
    AND users.status = 'Y'
    ORDER BY feature_log.time DESC

感谢您的支持!

1 个答案:

答案 0 :(得分:1)

因此,为了“静音”在给定用户的任何时间点已被“删除”的所有功能,您可以在以下子查询中添加(左)联接:

SELECT DISTINCT users.id as siteid, feature_log.featurecode, TRUE as mute_feature
FROM users
INNER JOIN feature_log ON (users.id = feature_log.siteid)
WHERE action = 'removed'

这将是给定用户在某个时间点禁用的功能列表。然后在您的查询的WHERE子句中,您将添加如下过滤器:

AND NOT IFNULL(mute_feature, FALSE)

基本上,这会使您的整个查询成为:

select users.id as site_id, users.company_name, feature_log.featurecode, feature.minimum_account as feature_type, users.account_type as site_type, account_types.name as account, feature_log.action, feature_log.time
from users
inner join
    feature_log
    on users.id = feature_log.siteid
left join (
    SELECT DISTINCT users.id as siteid, feature_log.featurecode, TRUE as mute_feature
    FROM users
    INNER JOIN feature_log ON (users.id = feature_log.siteid)
    WHERE action = 'removed'
) as muted_features ON (feature_log.siteid = muted_features.siteid AND feature_log.featurecode = muted_features.featurecode)
inner join 
    feature
    on feature_log.featurecode = feature.featurecode
inner join account_types
    on users.account_type_INC = account_types.id
where feature.minimum_account != 0
    AND feature.minimum_account > users.account_type
    AND users.status = 'Y'
    AND NOT IFNULL(mute_feature, FALSE)
    ORDER BY feature_log.time DESC