我正在试图弄清楚如何从价格<的表中选择3个相邻的行。当前商品价格。问题是如果我在表中选择第一行,第二行或第三行,我需要选择三个相邻的行围绕当前项目。重点需要放在较低价格的项目上,例如,如果我从表格中选择第三行,我需要选择前两行和第四行。这是我到目前为止的查询:
SELECT *
FROM (SELECT *
FROM temp_db_cart
WHERE airport='$airport'
AND people='$people'
AND price < '$price'
ORDER BY price DESC LIMIT 3
)
ORDER BY price ASC
示例数据:
+---------------+---------+--------+-------+
| hotel_name | airport | people | price |
+---------------+---------+--------+-------+
| Days Inn | MLB | 1 | 109 |
| Holiday Inn | MCO | 2 | 149 |
| Americas Best | MLB | 2 | 199 |
| Econo Lodge | SFB | 1 | 209 |
+---------------+---------+--------+-------+
预期结果:
精选酒店:Americas Best
+---------------+-------+---------+--------+-------+
| hotel_name | order | airport | people | price |
+---------------+-------+---------+--------+-------+
| Days Inn | 1 | .. | .. | .. |
| Holiday Inn | 2 | .. | .. | .. |
| Americas Best | Skip | .. | .. | .. |
| Econo Lodge | 3 | .. | .. | .. |
+---------------+-------+---------+--------+-------+
PHP / MySQL组合可用于答案。任何帮助将不胜感激。
答案 0 :(得分:1)
您可union
两张价格较低且价格较高的记录:
select * from
(
(SELECT *
FROM temp_db_cart
WHERE airport='MCO'
AND people='3'
AND price < '245'
ORDER BY price DESC LIMIT 3)
UNION
(SELECT *
FROM temp_db_cart
WHERE airport='MCO'
AND people='3'
AND price > '245'
ORDER BY price LIMIT 1)
)
order by price desc limit 3
在第一个查询中,您选择3行,在第二个查询中,选择1行(如果存在)。最后,在这些3+1
(或3+0
)行中,您只选择价格最高的3
行。
答案 1 :(得分:0)
SELECT *
FROM (SELECT MIN(price)
FROM temp_db_cart
WHERE airport='$airport'
AND people='$people'
AND hotel != '$hotel'
ORDER BY price DESC LIMIT 3
)
ORDER BY price ASC
答案 2 :(得分:0)
2小时后,我终于找到了解决方案。我将一个联合与两个选择查询组合在一起,选择3行(包括选定的酒店)和所选酒店后的3行。然后我设置limit 3
和order by price asc
以及一切它主要起作用。
SELECT *
FROM (
(
SELECT *
FROM temp_db_cart
WHERE price >= {$package['price']}
AND airport = '{$airport['abbr']}'
AND people = '{$travelers['number-of-travelers']}'
ORDER BY price ASC limit 3 )
UNION
(
SELECT *
FROM temp_db_cart
WHERE price < {$package['price']}
AND airport = '{$airport['abbr']}'
AND people = '{$travelers['number-of-travelers']}'
ORDER BY price DESC limit 3 ) ) AS u
WHERE hotel_name != '{$package['hotel_name']}'
ORDER BY price ASC limit 3;
编辑:父选择查询中3行的限制仅限制为联合集中的前3行。如何限制在所选酒店之前的2行开始并在联合子集的所选酒店之后的2行结束的偏移量?