Mysql查询结果围绕一些ID

时间:2012-01-24 15:00:58

标签: mysql sql

假设我有这样的表:

id: PRIMARY INT
price: INT (in dollars)
typeOfHouse: TINYINT (enumerated house types)

并且存在元组,假设(id = 3,price = 1243,typeOfHouse = 20)。

现在我想选择2个便宜的房子和2个费用较低的房子(2个,2个)。这可以通过两个查询(UNION)完成:

SELECT * FROM houses WHERE typeOfHouse=20 AND price>=1243 ORDER BY price LIMIT 3
SELECT * FROM houses WHERE typeOfHouse=20 AND price<=1243 ORDER BY price DESC LIMIT 3

这是一个假设的例子,条件通常要复杂得多,所以问题是 - 可以在一个查询中更快地完成这项工作,所以条件选择不会不得不进行两次。

2 个答案:

答案 0 :(得分:3)

你有什么好。您可以在一个查询中与UNION合并:

    SELECT * 
    FROM houses 
    WHERE typeOfHouse = 20       --- there may be more more houses
      AND price = 1243           --- with same price
UNION ALL
    SELECT * 
    FROM houses 
    WHERE typeOfHouse = 20 
      AND price > 1243 
    ORDER BY price 
    LIMIT 2
UNION ALL
    SELECT * 
    FROM houses 
    WHERE typeOfHouse = 20 
      AND price < 1243 
    ORDER BY price DESC 
    LIMIT 2

如果price上有索引,或者甚至更好 - (typeOfHouse, price)上的复合索引,则无需担心性能。

答案 1 :(得分:0)

您可以使用BETWEEN运算符,例如

SELECT * FROM houses WHERE typeOfHouse=20 AND price BETWEEN 1241 AND 1245 ORDER BY price