将WHERE和IN子句与两个字段组合在一起

时间:2011-02-11 22:37:27

标签: sql mysql database

我有一个包含3列(id,name,price)的'goods'表。我需要通过ID和价格范围列表获取数据。

我正在使用此查询:

SELECT id, name, price FROM goods
WHERE (id, price)
IN ((1,10), (3,20), (2,10))
ORDER BY FIELD(id, 1,3,2)

当我使用严格的价格值时,一切都很好。

事实上,我需要进行如下查询:

SELECT id, name, price FROM goods
WHERE (id, price)
IN ((1, BETWEEN 0 AND 100), (2, BETWEEN 50 AND 150), (n, BETWEEN m AND k))
ORDER BY FIELD(id, 1,3,n)

我发现表达式(1, BETWEEN 0 AND 100)永远不会返回我需要的结果,而(1,10)会。{/ p>

我肯定可以在php中按价格范围排除记录,但我正在尝试使用索引在mysql查询中找到更有效的方法。我该怎么办?

1 个答案:

答案 0 :(得分:4)

你不能像那样使用BETWEEN。尝试将IN表达式更改为一系列OR:

SELECT id, name, price
FROM goods
WHERE
    (id = 1 AND price BETWEEN 0 AND 100) OR
    (id = 2 AND price BETWEEN 50 AND 150) OR
    (id = n AND price BETWEEN m AND k)
ORDER BY FIELD(id, 1,3, n)