首页 > 解决方案 > 多个限制,其中价格 1 <> 价格 2

问题描述

我正在使用 mysql 和 php。

假设我的数据库中有超过 400.000 本书的下表:

+------+-------+--------+--------+
| Item | color | Price1 | Price2 |
+------+-------+--------+--------+
|    1 | blue  |   1.23 |   1.23 |
|    2 | red   |   2.34 |   2.66 |
|    3 | green |   4.55 |   4.55 |
|    4 | blue  |   2.33 |   2.44 |
|    5 | blue  |   3.44 |   3.66 |
|    6 | blue  |   4.55 |   4.66 |
|    7 | ...   |    ... |    ... |
+------+-------+--------+--------+

我想获得 price1 <> price2 的每种颜色的前 5 个条目。如果受影响的行小于 5 ==> 那么我想让查询填充 price1==price2 的条目。

如果是“蓝色”,我想得到以下结果:

+------+-------+--------+--------+
| Item | color | Price1 | Price2 |
+------+-------+--------+--------+
|    4 | blue  |   2.33 |   2.44 |
|    5 | blue  |   3.44 |   3.66 |
|    6 | blue  |   4.55 |   4.66 |
|    1 | blue  |   1.23 |   1.23 |
+------+-------+--------+--------+

我有一些解决方法来做到这一点:

SELECT * FROM books WHERE color = 'blue' AND price1<>price2 ORDER BY price1 LIMIT 5;

获取受影响的行。在此示例中: 3. 启动另一个查询:

SELECT * FROM books WHERE color = 'blue' price1=price2 ORDER BY price1 LIMIT 2;
//Limit 2, because I ve already 3 rows from the first result.

有没有办法合并这个查询?

标签: phpmysqldatabase

解决方案


您可以对每种颜色的行进行排序,以便price1 <> price2首先出现带有的行。您可以使用窗口函数
实现此条件排序:ROW_NUMBER()

SELECT t.Item, t.color, t.Price1, t.Price2  
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY color ORDER BY price1 <> price2 DESC, price1) rn
  FROM books 
) t
WHERE t.rn <= 5

如果您想要特定颜色的结果:

SELECT *
FROM books 
WHERE color = 'blue'
ORDER BY price1 <> price2 DESC, price1
LIMIT 5

推荐阅读