我想要一个MySql查询获得5行,其中包括最小价格行,最大价格行和其他3个随机行.
表:
ID Product Price
1 data 2
2 data 20
3 data 55
4 data 24
5 data 2
6 data 15
7 data 10
8 data 33
9 data 3
10 data 30
Run Code Online (Sandbox Code Playgroud)
预期结果(随机3行)
ID Product Price
1 data 2
3 data 55
4 data 24
6 data 15
7 data 10
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
小智 10
SELECT table.*
FROM table
, ( SELECT @minPrice := ( SELECT min(Price) FROM table ) minPrice
, @minId := ( SELECT id FROM table WHERE Price = @minPrice ORDER BY rand() LIMIT 1 )
, @maxPrice := ( SELECT max(Price) FROM table ) maxPrice
, @maxId := ( SELECT id FROM table WHERE Price = @maxPrice ORDER BY rand() LIMIT 1 )
) tmp
WHERE table.id in (@minId,@maxId)
UNION
(SELECT *
FROM table
WHERE Price not in (@minPrice,@maxPrice)
ORDER BY rand()
LIMIT 3
)
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以这样做,
select * from table order by Price asc limit 0,1
union all
select * from table order by Price desc limit 0,1
union all
select * from table order by RAND() limit 0,3
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
778 次 |
最近记录: |