Laravel / Mysql groupby订购

时间:2016-10-03 14:57:03

标签: php mysql laravel group-by sql-order-by

我有命令

 SELECT * FROM 
    (SELECT * FROM episodes ORDER BY created_at DESC) and t1 
 GROUP BY serial_id 
 ORDER BY created_at DESC

我将返回由created_at添加的最后一集的系列。但问题是,当我把它托管一切都工作但现在我把它放在VPS服务器上,我总是列出第一集。如果我在desc工作之后添加group by serial_id,但在laravel(-> groupBy ('serial_id')

上无法实现

共享托管:

+---------+-------------+--------+
| id      | serial_id   | part   |
+---------+-------------+--------+
|    8124 | 12          | s02e10 |
|     362 | 8           | s09e12 |
|    4673 | 9           | s01e12 |
|     871 | 4           | s03e24 |
+---------+-------------+--------+

我的VPS:

+---------+-------------+--------+
| id      | serial_id   | part   |
+---------+-------------+--------+
|    8124 | 12          | s01e01 |
|     362 | 8           | s01e01 |
|    4673 | 9           | s01e01 |
|     871 | 4           | s01e01 |
+---------+-------------+--------+

提前感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您的查询中似乎有很多错误。

FROMORDER BY

之间缺少一个表名
SELECT * FROM (SELECT * FROM 
--                         ^^ where is the tablename ?

ORDER BY episodes created_at DESC) and t1 GROUP BY ORDER BY serial_id created_at DESC
--               ^^ missing comma,  ^^ this 'and' seems in the wrong place and you havent't column for group by and in last another missing comma

尝试这样的事情:

SELECT * FROM ( SELECT * 
            FROM  my_table  ORDER BY episodes,  created_at DESC)  t1 
GROUP BY my_column_for_group_by  
ORDER BY serial_id, created_at DESC

在laravel中,您可以使用以下方式指定订单方向:

 ->orderBy('serial_id')
 ->orderBy('created_at',  'DESC')

答案 1 :(得分:0)

在这种情况下,您可能必须使用RAW:groupBy(DB::raw('serial_id desc'))

如下所示

DB::table( DB::raw("(SELECT * FROM episodes ORDER BY created_at DESC) and t1") )->groupBy(DB::raw('serial_id desc'))->orderBy('created_at', 'desc')->get();