laravel orderby列值错误

yi0zb3m4  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我尝试按列值对结果排序,但它不起作用

$users = Comment::select([
            'id',
            'comment',
            'user_name',
            'product_id',
            'rating',
            'country',
            'status',
            'pin',
            'created_at',
        ])->where('shop_name',$shop)->where('product_id', $id)->with('images')->orderByRaw("IF(product_url = 'customer')  DESC")->orderByRaw("product_url = manually ASC")->orderBy('pin', 'desc')->orderBy('rating', 'desc')->with('pages')->get();

我添加了这个代码

->orderByRaw("IF(product_url = 'customer')  DESC")

我得到这个错误
“sqlstate[42000]:语法错误或访问冲突:1064您的sql语法有错误;请查看与您的mysql服务器版本对应的手册,以获取使用near')desc,product\u url=manually asc, pin 描述, rating 第1行的描述(sql:select) id , comment , user_name , product_id , rating , country , status , pin , created_atcomments 哪里 shop_name =和 product_id =order by if(product\U url='customer')desc,product\U url=manually asc, pin 描述, rating 描述)

vxf3dgd4

vxf3dgd41#

mysql数据库 IF 函数有三个参数。
此表达式无效:

IF(product_url = 'customer')

因为只有一个参数提供给 IF() 功能。
我们可以这样做:

IF(product_url = 'customer',1,0)

这相当于更符合ansi标准

CASE WHEN product_url = 'customer' THEN 1 ELSE 0 END

mysql速记也可以

ORDER BY product_url = 'customer'   DESC

相当于

ORDER BY CASE
           WHEN product_url = 'customer' THEN 1 
           WHEN product_url IS NOT NULL  THEN 0
           ELSE NULL
           END   DESC

相关问题