我想要一个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
预期结果(包含3个随机行)
ID Product Price
1 data 2
3 data 55
4 data 24
6 data 15
7 data 10
任何帮助都将不胜感激!
发布于 2017-06-17 14:07:04
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
)
发布于 2017-06-17 11:25:22
你可以这样做,
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
发布于 2017-06-24 10:27:56
可以通过UNION和sub查询得到:
(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 WHERE Price NOT IN ( SELECT CONCAT( MIN( `Price` ) , ',', MAX( `Price` ) ) AS MaxPrice FROM table ) ) ORDER BY RAND( ) LIMIT 0 , 3 )
https://stackoverflow.com/questions/44565328
复制相似问题