我有以下表格:
UserAction:
type_action:string
entity_id:int
日期:日期时间
user_id:int(引用用户)
的问题:
text:string
user_id:int(引用用户)
回答:tinyint
的 EntityTracker
type_track:string
entity_id:int
动作:字符串
日期:日期时间
我需要知道满足这些条件的EntityTracker(alias et)中有多少(计数)记录:
- action ='ANSWERED'
- type_track ='问题'
- 日期>比(UserAction(别名ua)中的记录日期与ua.entity_id = et.entity_id和ua.type_action = et.type_track)
- entity_id符合条件:id = et.entity_id的问题有user_id = params [:user_id]
所以我必须加入Question和UserAction。
有什么帮助吗?
答案 0 :(得分:1)
也许是这样的:
EntityTracker.find(:all,
:from => 'entity_trackers et',
:select => 'COUNT(et.id) AS count',
:conditions => ['et.action = ? AND
et.type_track = ? AND
et.date > (SELECT MAX(ua.date)
FROM user_actions ua
WHERE ua.entity_id=et.entity_id AND
ua.type_action=et.type_track) AND
EXISTS (SELECT questions.id
FROM questions
WHERE questions.id=et.entity_id AND
questions.user_id=?)',
'ANSWERED', 'QUESTION', user_id])