我正在尝试创建一个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
答案 0 :(得分:1)
你有正确的想法。但是,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