2011-11-10 70 views
0

做一些調查和寫一個日誌數據庫的查詢。幫助MySQL查詢 - 省略,分組?

我已經加入了很多表來恢復我需要的數據,但我想清理一下。

該查詢返回所有用戶以及他們的帳戶上啓用了哪些功能。

這裏是我想要做的清理:

他們的是一種叫做有兩種狀態的行動「,「添加」和「刪除」

如果用戶特徵列有'刪除'的行動,那麼我想不顯示任何行的同一功能,該用戶也被標記爲'添加'

這可能嗎?!

這是我到目前爲止有:

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 

感謝您的支持!

+0

多大'feature_log'表?性能在此查詢的上下文中是否重要? (我可以看到你可能需要使用從屬子查詢或左連接,這可能非常慢) – Romain

+0

只有大約8K行,性能並不重要,因爲它只是一次性調查 – adamtor45

回答

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 
+1

羅曼,如果我們曾經穿過路徑,我給你買啤酒!謝謝,這工作完美! – adamtor45

+1

@ adamtor45我會記住這個:)無論如何,這並不難 - 你只需要一點點練習就可以自己做到這一點。 – Romain