我有这样的SQL查询:
SELECT Code
FROM xyz
WHERE xyz.Code IN ('20','10') AND price =
(select min(price) FROM xyz WHERE CODE IN ('20','10'));
查询后的所需输出:10
表xyz: -
价格:1 2 1
代码:10 20 30
有没有更好的方法来编写这个sql语句?因为在我的sql语句中“WHERE CODE IN('20','10')”重复两次,我试图避免两次调用此语句
答案 0 :(得分:6)
如果您只想接收一行,可以使用ORDER BY和LIMIT:
SELECT Code
FROM xyz
WHERE xyz.Code IN ('20','10')
ORDER BY price
LIMIT 1
答案 1 :(得分:0)
您可以使用join
来过滤,而不是where in
条件。这将允许您让连接表重用第一个表中的条件。
select Code
from (
select *
from xyz
where code in ('20','10')
) t1
inner join
(
select code
, min(price) as min_price
from xyz
group by
code
) filter
on filter.code = t1.code
and filter.min_price = t1.price