我有一个这样的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')“被重复了两次,而我试图避免调用该语句两次
发布于 2011-12-08 19:57:12
如果只想接收一行,可以使用ORDER BY和LIMIT:
SELECT Code
FROM xyz
WHERE xyz.Code IN ('20','10')
ORDER BY price
LIMIT 1发布于 2011-12-08 20:00:25
您可以使用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.pricehttps://stackoverflow.com/questions/8430657
复制相似问题