2014-10-20 19 views
0

我有3個表。 表1的用戶, 表2 researchReq, 表3研究查詢列表每個2-uple字段的單行

researchReq表有一定的要求,我用它來檢查用戶是否適合於特定的研究(如min_agemax_age和更多)和INT字段( NUM_OF_DAYS)。 research表具有用於researchReq的FK,用戶的FK,日期字段和一些更多信息。在適合任何researchReq的用戶中,我需要所有最後research寄存器在researchReq.num_of_days以及那些沒有任何research寄存器的那些用戶。

例如

User 
# | age 
1 | 20 
2 | 19 
3 | 21 

researchReq 
# | min_age | max_age | num_of_days 
1 | 15  | 25  | 20 
2 | 25  | NULL | 30 

research 
# | req_id | user_id | date 
1 | 1  | 3  | 2014-08-20 
2 | 1  | 3  | 2014-09-20 
3 | 1  | 3  | 2014-10-20 
4 | 1  | 2  | 2014-08-20 
5 | 1  | 2  | 2014-09-20 

在這種情況下,所有3個用戶都適合researchReq #1

* min_age和max_age可以爲空。如果它們是空的,我需要disconsider時,即時通訊,如果用戶符合

user_id | researchReq_id | last 
1  | 1    | null 
2  | 1    | 30 

用戶#1不要有任何寄存器,所以「最後」爲null檢查。

用戶#2的最後一個註冊時間超過20天,所以我列出他和他的時間間隔。

由於research的最後一個註冊用戶#3沒有超過20天,我不需要他。

我想是這樣的:

select ur.user_id, ur.req_id ,datediff(curdate(),ri.date) as last 
from 
    (
     select u.id as user_id, r.id as req_id, r.num_of_days as n_days 
     from user u 
     join researchReq r 
      on (r.min_age is null or datediff(curdate(),u.age) >= r.min_age) 
      and (r.max_age is null or datediff(curdate(),u.age) <= r.max_age) 
    ) as ur 
left join research ri 
    on ur.user_id = ri.user_id and ur.req_id = ri.req_id 
having last > ur.n_days 

但是我有一個問題。此查詢列出了每個用戶的所有research ri註冊表,我只需要每個ri.user_idri.req_id(如複合PK)的最後一個日期的註冊表。我不能使用group by user_id,因爲它可能有兩個或更多的區別ri.req_id

我只是不知道如何做到這一點。 Ty有任何幫助,併爲我的英語不好而感到抱歉。

@edit

如果用戶有研究與FK爲2個或更多researchReq,該查詢會給我所有researchReq的分鐘(DATEDIFF())。我需要一個接一個,如:

user_id | researchReq_id | last 
1  | 1    | null 
2  | 1    | 30 
2  | 2    | 15 

查詢返回

user_id | researchReq_id | last 
1  | 1    | null 
2  | 1    | 15 
2  | 2    | 15 

回答

0

我不是100%肯定我明白你的要求,但是這至少再現,你正在尋找的答案您提供的數據。

select u.user_id, r.id as researchReq_id, u.last from (
    select u.id as user_id, u.age, min(datediff(now(), date)) as last 
     from user u 
     left join research r on r.user_id = u.id 
     group by u.id 
     having last is null or last > 20) as u 
join researchReq r 
on (r.min_age is null or u.age >= r.min_age) 
      and (r.max_age is null or u.age <= r.max_age) 

Link to SQL Fiddle

+0

請檢查我的編輯 – 2014-10-20 18:29:55

+0

在你的編輯,什麼是第一和第二組結果之間的差異? – 2014-10-20 18:41:21

+0

re edit ..查詢返回由u.id分組的min(datediff()),不管什麼是researchReq_id。我知道這是查詢的預期,但我需要類似min()的user_id和researchReq_id組。 – 2014-10-20 19:39:33

相關問題