php - 多个限制,其中价格 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.
有没有办法合并这个查询?
解决方案
您可以对每种颜色的行进行排序,以便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
推荐阅读
- javascript - DEPTH_FUNC中图像的JavaScript p5js WEBGL透明度颜色不起作用
- spring-boot - 如何将 SpringBoot 属性加载到 log4j.xml
- hadoop - 在 PIG 上的包中提取元组的元素
- assembly - 汇编函数来计算给定字符串的长度
- c++ - 调试时如何获取VC++错误的来源
- javascript - 如何修复provlem表和选择?
- sql - 截断计算列的结果
- typescript - 打字稿条件约束字符串联合
- python - 用前一个单词的字母反向替换每个单词的第一个字母
- javascript - 将今天的日期分配给键并引用此键以添加 5 天