面对在laravel中编写sql查询的困难

时间:2016-01-02 07:55:45

标签: php mysql sql laravel

我们有三个表用户,答案和延伸。当有人登录我们的系统时,我们在延伸表中存储了user_id,created_at和updated_at,当他/她注销更新时,在同一行中删除了。

会议时间30分钟。

用户表

  • id
  • f_name
  • l_name
  • 电子邮件

答案表

  • ID
  • USER_ID
  • created_at
  • 的updated_at

拉伸表

  • id
  • user_id
  • created_at
  • updated_at
  • deleted_at

现在我想只从伸展表中获得已给出答案的那些行。我写了这个查询,但需要花费很多时间,但没有返回准确的数据。

  $query = "select count(a.id), a.user_id
      from answers a
      where a.created_at in 
            (select s.created_at 
                from stretches s 
                   where s.created_at >= a.created_at
            ) group by a.user_id";
  $results = DB::select(DB::raw($query)); 

我很想知道你们有些人是怎么写这个问题的。

答案表

id | body | user_id |    created_at    |    updated_at 
10 | text |   10    | 2015-10-10 0:0:0 | 2015-10-10 0:0:0 

延伸表

id | user_id |    created_at    |    updated_at    |    deleted_at 
 1 |   10    | 2015-10-00 0:0:0 | 2015-10-10 0:0:0 | 2015-10-20 0:0:0 

现在我想从stretches表中获取已给出答案的那些行。

查询结果应为:

id | user_id |    created_at    |   updated_at    |    deleted_at 
 1 |   10    | 2015-10-10 0:0:0 |2015-10-10 0:0:0 | 2015-10-10 0:0:0

2 个答案:

答案 0 :(得分:0)

如果我理解你的话。下面的SQL查询将仅返回表Stretches中为用户提供答案的记录。使用运算符 JOIN ,它将为您进行过滤工作。

SELECT S.user_id, COUNT(*) as answers_count FROM Stretches AS S
    JOIN Answers AS A ON S.user_id = A.user_id
GROUP BY S.user_id

答案 1 :(得分:0)

这应该可以完成工作

SELECT DISTINCT Stretches.* FROM Stretches
    JOIN Answers ON Stretches.user_id = Answers.user_id
GROUP BY Stretches.user_id