在mysql中按顺序分组

时间:2015-06-08 09:00:31

标签: mysql

我有一个像这样的表结构:

股票表

id  stock
1   0
2   113
3   34
4   50

产品表(两个表都与ID列连接)

id   parid   name
1    1       A
2    1       B
3    2       C
4    3       D

我在我的查询中使用了parid分组,这是我项目的要求。

查询:

select * 
from products as p inner join 
     stock as s on p.id=s.id 
group by parid 
order by stock DESC

显示结果为:

id  parid   name
4   3       D
3   2       C
1   1       A

我想要的是:

Group by应按照产品库存的顺序包含产品。

所以查询应该取得低于结果而不是上面的结果:

id  parid  name
4   3      D
3   2      C
2   1      B

任何帮助将不胜感激。

这可能是一个答案

使用以下两个答案,我想出了下面的查询,目前似乎解决了这个问题(仍然需要检查多个案例)。

SELECT * FROM products p inner join stock i on p.id=i.id inner join (select max(stock) maxstock,parid from products inner join stock on products.id=stock.id group by parid) q on q.parid=p.parid and q.maxstock=i.stock group by p.parid

2 个答案:

答案 0 :(得分:3)

尝试运行:

select * 
from products as p inner join 
     stock as s on p.id=s.id 
where stock in (select max(stock) from products as p inner join 
     stock as s on p.id=s.id  group by parid)
group by parid 
order by stock desc

答案 1 :(得分:0)

考虑以下中间结果:

SELECT p.*
     , s.stock
  FROM products p
  JOIN stock s
    ON s.id = p.id
  JOIN 
     ( SELECT p.parid
            , MAX(stock) max_stock
         FROM products p
         JOIN stock s
           ON s.id = p.id
        GROUP
           BY p.parid
     ) y
    ON y.parid = p.parid
   AND y.max_stock = s.stock;

选择行ID 2而不是行ID 1的标准是什么?

根据您迄今为止的评论,我认为我之前的答案是正确的。如果这是错的,那是因为你对这个问题的表达是错误的。

SELECT a.*
  FROM 
     ( SELECT p.*
            , s.stock
         FROM products p
         JOIN stock s
           ON s.id = p.id
         JOIN 
            ( SELECT p.parid
                   , MAX(stock) max_stock
                FROM products p
                JOIN stock s
                  ON s.id = p.id
               GROUP
                  BY p.parid
            ) y
           ON y.parid = p.parid
          AND y.max_stock = s.stock
     ) a
  LEFT
  JOIN
     ( SELECT p.*
            , s.stock
         FROM products p
         JOIN stock s
           ON s.id = p.id
         JOIN 
            ( SELECT p.parid
                   , MAX(stock) max_stock
                FROM products p
                JOIN stock s
                  ON s.id = p.id
               GROUP
                  BY p.parid
            ) y
           ON y.parid = p.parid
          AND y.max_stock = s.stock
     ) b
    ON b.parid = a.parid
   AND b.id < a.id
 WHERE b.id IS NULL;
+------+-------+------+-------+
| id   | parid | name | stock |
+------+-------+------+-------+
|    1 |     1 | A    |   113 |
|    3 |     2 | C    |     0 |
|    4 |     3 | D    |    50 |
+------+-------+------+-------+

扩展这个想法来解决关系,我们可以使用另一种技术......

selectize.js