简体   繁体   English

MySql查询根据价格获得类似的结果

[英]MySql query to get similar results based on price

Don't know if the title for this question is ok, but my problem is simple. 不知道这个问题的标题是否合适,但我的问题很简单。
I have a list of results and for simplicity, it contains only an id and a price : 我有一个结果列表,为简单起见,它只包含一个id和一个price

+----+-------+
| id | price |
+----+-------+
| 11 |   10  |
| 52 |   17  |
| 23 |   45  |
| 24 |   50  |
| 55 |   60  |
| 96 |   70  |
|  7 |   75  |
| 78 |   80  |
| 99 |   100 |
+----+-------+

For a given id/price, I need to find first 2 records with a lower price and next 2 with a higher price. 对于给定的ID /价格,我需要找到价格较低的前2条记录,然后是价格较高的2条记录。

For example, for id = 55 and price = 60, the results would be: 例如,对于id = 55和price = 60,结果将是:

+----+-------+
| id | price |
+----+-------+
| 23 |   45  |
| 24 |   50  |

| 96 |   70  |
|  7 |   75  |
+----+-------+

In a rough implementation, this can be of-course obtained with a UNION, like this: 在粗略的实现中,这可以通过UNION获得,如下所示:

SELECT id, price
FROM MyTable
WHERE price <= 60 AND id != 55
ORDER BY price DESC
LIMIT 0,2

UNION ALL

SELECT id, price
FROM MyTable
WHERE price >= 60 AND id != 55
ORDER BY price ASC
LIMIT 0,2

But given the fact that MyTable is actually a view, obtained using a complex query behind, is there another way to achieve this? 但鉴于MyTable实际上是一个使用后面的复杂查询获得的视图,还有另一种方法可以实现吗?

I was even thinking that instead of running the query twice (with the UNION), to get all the results in one query and then to use PHP to find the 4 results. 我甚至认为不是运行查询两次(使用UNION),而是在一个查询中获取所有结果,然后使用PHP查找4个结果。

You have to check this: Your query 你必须检查这个:你的查询

SELECT id, price FROM (
SELECT @rank:=@rank+1 AS rank, @selectedRank := IF(id = 55, @rank,
@selectedRank), id, price
  FROM ( SELECT id, price FROM MyTable ORDER BY price
  ) t1, (SELECT @rank:=0) t2, (SELECT @selectedRank:=0) t3
) results
WHERE rank != @selectedRank AND rank BETWEEN @selectedRank - 2 AND @selectedRank + 2;

And this is what query explain shows: 这就是查询解释显示的内容: MySQL Workbench解释查询 And this is another one: 这是另一个:

SELECT * FROM test.mytable
WHERE
price >= (SELECT price FROM MyTable
    WHERE price <= 60
    ORDER BY price DESC
    LIMIT 2,1)
 and id != 55
ORDER BY price
LIMIT 4;

Which Query explain shows for it: 哪个查询解释显示: MySQL Workbench中的查询说明

Thanks to @David Packer's hint and to this link , I found the solution to iterate the table only once: 感谢@David Packer的提示和这个链接 ,我找到了只迭代表一次的解决方案:

SELECT id, price 
FROM (
  SELECT @rank:=@rank+1 AS rank, @selectedRank := IF(id = 55, @rank, @selectedRank), id, price
  FROM (
    SELECT id, price
    FROM MyTable
    ORDER BY price
  ) t1, (SELECT @rank:=0) t2, (SELECT @selectedRank:=0) t3
) results
WHERE rank != @selectedRank
AND rank BETWEEN @selectedRank - 2 AND @selectedRank + 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM