我想在select语句中使用这个子查询
select category from `categories` WHERE id = `products`.`category_id`
这是我方法的select语句部分
$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 ')
);
错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select category from `categories` WHERE id = `products`.`category_id` )
我讨厌使用直接选择语句。因为我改变数据库是不好的。
尽管使用直接选择语句但它无效。我怎么能这样做?
答案 0 :(得分:2)
只需更新以下声明
即可DB::raw('('.DB::select('select category from `categories` WHERE id = `products`.`category_id` ').') AS category ')
进入
DB::raw('(select category from `categories` WHERE id = `products`.`category_id`) AS category')
此处的错误是针对未知列products.category_id
,您需要检查表中是否有category_id
答案 1 :(得分:0)
请按照以下示例查看其中一个子查询:
$result = static::select('id')
->where( 'id', '!=', $currentLevelId)
->where('level', '>', DB::raw("(SELECT level FROM " . $this->table . " WHERE id='".$currentLevelId."')") )
->orderBy('level')->first();
结果查询:
SELECT * FROM `approval_levels` WHERE `id` != 2 AND `level` > (SELECT LEVEL
FROM approval_levels WHERE id='2') ORDER BY `level` ASC LIMIT 1
希望它有所帮助!