Laravel 5.2 Select 语句中的子查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34870957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subquery in Select Statement in Laravel 5.2
提问by Cihan Küsmez
I want to use this subquery in select statement
我想在 select 语句中使用这个子查询
select category from `categories` WHERE id = `products`.`category_id`
Here is select statement part of my method
这是我的方法的选择语句部分
$query = $this->select(
DB::raw('COUNT(DISTINCT(`order_details`.`product_id`)) as productCount'), 'products.category_id',
DB::raw('('.DB::select('select category from `categories` WHERE id = `products`.`category_id` ').') AS category ')
);
Error:
错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select category from `categories` WHERE id = `products`.`category_id` )
I hate using direct select statement. Because it is not good if i will change database.
我讨厌使用直接选择语句。因为如果我更改数据库就不好。
Despite of using direct select statement it is not working. How can i do that ?
尽管使用直接选择语句它不起作用。我怎样才能做到这一点 ?
回答by Narendrasingh Sisodia
Simply update your following statement
只需更新您的以下声明
DB::raw('('.DB::select('select category from `categories` WHERE id = `products`.`category_id` ').') AS category ')
into
进入
DB::raw('(select category from `categories` WHERE id = `products`.`category_id`) AS category')
Over here the error is for unknown column products.category_id
you need to check are you have category_id
within your table
在这里,错误是未知列,products.category_id
您需要检查category_id
您的表中是否有
回答by rc.adhikari
Please follow the example below for one of the subquery:
请按照下面的示例获取子查询之一:
$result = static::select('id')
->where( 'id', '!=', $currentLevelId)
->where('level', '>', DB::raw("(SELECT level FROM " . $this->table . " WHERE id='".$currentLevelId."')") )
->orderBy('level')->first();
Outcome Query:
结果查询:
SELECT * FROM `approval_levels` WHERE `id` != 2 AND `level` > (SELECT LEVEL
FROM approval_levels WHERE id='2') ORDER BY `level` ASC LIMIT 1
Hope it helps!
希望能帮助到你!