MySQL-从每个组中仅选择2行

2022-03-04 00:00:00 sql database row mysql

我正在尝试创建将用作显示信息的过滤的query

具体地说,我希望此查询最多显示2行具有相同position值的行。

到目前为止,我已经编写了此代码,但它只显示了每个类别中的一个,我不确定我做错了什么,您能帮助我吗?

SELECT name, surname, position, value, points FROM
    (SELECT name, surname, position, value, points, 
    @num := IF(@type = position, @num + 1, 1) AS row_number,
    @type := position AS dummy 
    FROM players 
    WHERE (name LIKE '%$searchphrase%' OR surname LIKE '%$searchphrase%') 
    AND value >= '$minvalue'
    AND value <= '$maxvalue'
    GROUP BY position) AS x WHERE x.row_number <= 2
ORDER BY
    CASE WHEN $filter=0 THEN points END DESC, 
    CASE WHEN $filter=1 THEN points END ASC,
    CASE WHEN $filter=2 THEN value END DESC,
    CASE WHEN $filter=3 THEN value END ASC,
    CASE WHEN $filter=4 THEN surname END DESC,
    CASE WHEN $filter=5 THEN surname END ASC

解决方案

您的想法是对的。但是,MySQL不保证表达式的求值顺序。另外,子查询中有group by position

所以我认为您可能需要:

SELECT . . .
FROM (SELECT name, surname, position, value, points, 
             (@num := if(@type = position, @num + 1,
                         if(@type := position, 1, 1)
                        )
             ) AS row_number
      FROM players p CROSS JOIN
           (SELECT @num := 0, @type := '') params
      WHERE (name LIKE '%$searchphrase%' OR surname LIKE '%$searchphrase%') AND
            value >= '$minvalue' AND value <= '$maxvalue'
      ORDER BY position
     )  x
WHERE x.row_number <= 2

相关文章