2014-10-01 56 views
0

我的问题非常简单的表现就是:取得成果取决于基于时间的条件

评论

| mentor_id | mentee_id | status | created | 
| 1   | 2   | active | 2014-08-13 | 
| 1   | 2   | inactive | 2014-08-20 | 
| 1   | 2   | inactive | 2014-08-27 | 
| 1   | 3   | inactive | 2014-08-20 | 
| 1   | 2   | inactive | 2014-09-03 | 

用户表

| id | first_name | last_name | 
| 1 | Ivan  | Pietro | 
| 2 | Alexander | Summers | 
| 3 | Mark  | Xavier | 

学长表

| id | mentee_id | mentor_id | created | 
| 1 | 2   | 1   | 2014-08-06 | 
| 2 | 3   | 1   | 2014-08-06 | 

mentor_idmentee_id是用户表的ID。

我想要得到的users.idusers.first_nameusers.last_name具有的inactive在过去14天status他们在辅导表创建后的学弟学妹(user表)。

+0

在哪里存储这些评论?你需要选择你想要的w/e,在mentee_id上​​加入用户表,然后按创建顺序排列,并且限制为2。 – Solrac 2014-10-01 08:17:43

+0

[SQL Counting Records with Count and Having]的可能重复(http://stackoverflow.com/questions/4912792/sql-counting-records-with-count-and-having) – bodi0 2014-10-01 08:19:47

+0

评论存储在评论表 – 2014-10-01 08:23:43

回答

0

你的问题是不清澈,但我认为你所要求的:

SELECT DISTINCT u.* 
FROM reviews r 
JOIN mentorship m 
     ON m.mentee_id = r.mentee_id AND m.mentor_id = r.mentor_id 
JOIN user u 
     ON u.id = r.mentee_id 
WHERE r.status = 'inactive' 
AND  DATEDIFF(r.created, m.created) >= 14 

这将使你:

id first_name last_name 
-- ---------- ---------- 
2 Alexander Summers 
3 Mark  Xavier 

这是很难知道这是什么因为数据集是有限的(无论如何,只有2个参与者)。
希望是!

+0

有人比我快;-)另见http://sqlfiddle.com/#!2/f0a2f/16/0 – SGeis 2014-10-01 09:47:58

0

这样的事情? (CURDATE()用于MySQL,如果使用不同的SQL,则必须查看它)。

SELECT users.* 
FROM users, reviews 
WHERE reviews.mentee_id = users.id AND reviews.status = 'inactive' AND DATEDIFF(reviews.created, CURDATE()) >= 14; 
+0

你很近,但它必须是创建导师记录的日期而不是'CURDATE()' – 2014-10-01 09:01:23

1

入住这

select user.id,user.first_name,user.last_name,max(Reviews.created) RCreated, Mentorship.created MCreated 
    from Reviews 
    inner join User on Reviews.mentee_id=USer.id 
    inner join Mentorship on Reviews.mentee_id=Mentorship.mentee_id 
    where status='inactive' 
    group by User.id 
    having DATEDIFF(RCreated, MCreated) >= 14 

http://sqlfiddle.com/#!2/dfc71/26

+0

+1伟大的解决方案 – 2014-10-03 10:01:22