如何在groupby列产品表之前订购并显示独特和可用的产品

时间:2017-03-13 14:41:02

标签: php laravel subquery sql-order-by

我在laravel查询中遇到了问题:

我想在分组之前按相同的列排序, 例如:

产品表

id ....... cat_id ....... color_id ....... count<br>
---------------------------------------------------------<br>
1 ........... 27 ............... 3 ............... 0
<br>
2 ........... 27 ............... 7 ................ 3
<br>
3 ........... 27 ............... 3 ................ 10
<br>
4 ........... 27 ............... 3 ................ 2

现在:我想先用 orderby'ount'来结果,所以 groupby'cat_id,color_id'

id ....... cat_id ....... color_id ....... count<br>
---------------------------------------------------------<br>
3 ........... 27 ............... 3 ............... 10
<br>
2 ........... 27 ............... 7 ................ 3

3 个答案:

答案 0 :(得分:0)

假设您的查询类似于

SELECT id, cat_id, color_id, count FROM products

count是数据库中的值,您只需合并GROUP BYORDER BY语句:

SELECT id, cat_id, color_id, count FROM products GROUP BY cat_id, color_id ORDER BY count

使用此查询,很多结果丢失。如果您想结合使用count的值,可以使用GROUP_CONCAT

SELECT id, cat_id, color_id, GROUP_CONCAT(count) FROM products GROUP BY cat_id, color_id ORDER BY count

使用此查询,您仍会获得所有相关信息,但对于cat_idcolor_id列中的每个条目,您将获得逗号分隔的count值的字符串。

这里有一些链接可以获得w3schools的更多信息:

答案 1 :(得分:0)

请试试这个

select pr_l.* 
from products pr_l
inner join (
     select 
     cat_id, color_id,max(count) as count 
     from products
     group by `cat_id`,`color_id`
  ) pr_r
on pr_l.count = pr_r.count and pr_l.cat_id = pr_r.cat_id and  pr_l.color_id = pr_r.color_id   
order by count desc

通常'在'by by'之前'order by'不起作用。所以我已经使用内联接产品表

左边的产品表有所有记录,右边的产品表有最大计数行,分组有cat_id和color_id

用于laravel sql语法

$products = $products->select(DB::raw('pr_l.*'))->from(
DB::raw('inner join (
 select 
 cat_id, color_id,max(count) as count 
 from products
 group by `cat_id`,`color_id`
) pr_r')
)->where(pr_l.count = pr_r.count and pr_l.cat_id = pr_r.cat_id and  pr_l.color_id =   pr_r.color_id)->orderBy('count', 'desc');

答案 2 :(得分:-1)

如何转换:

select l.* 
from products l
inner join (
     select 
     cat_id, color_id,max(count) as count 
     from products
     group by `cat_id`,`color_id`
  ) r
on l.count = r.count and l.cat_id = r.cat_id and  l.color_id = r.color_id   
order by count desc

laravel elequent语法看起来像:

$products = $products->select(DB::raw('l.*'))->from(
    DB::raw('inner join (
     select 
     cat_id, color_id,max(count) as count 
     from products
     group by `cat_id`,`color_id`
  ) r')
)->where(l.count = r.count and l.cat_id = r.cat_id and  l.color_id = r.color_id)->groupBy(['products_id','color'])->orderBy('count', 'desc');