MySQL中的ORDER BY RAND()

fis*_*man 2 mysql sql sql-order-by

我想使用ORDER BY RAND()查询mysql.但我有一些问题想问.

我的mysql表'image'像:

id | image | width | height |
1  | 1.jpg | 640   | 480    |
2  | 2.jpg | 800   | 600    |
3  | 3.jpg | 480   | 600    |
4  | 4.jpg | 720   | 480    |
5  | 5.jpg | 600   | 800    |
6  | 6.jpg | 1024  | 768    |
7  | 7.jpg | 768   | 1024   |
8  | 8.jpg | 800   | 600    |
9  | 9.jpg | 720   | 560    |
10 | 10.jpg| 800   | 600    |
Run Code Online (Sandbox Code Playgroud)

我需要做一个mysql查询ORDER BY RAND()打印5 images,命令是:

first: width >= 720 and height >= 560 , 1 image(this may be width < height)

second: width > height, 2 images.(left the first 1 image, do the rest 9 images ORDER BY RAND())

third: width >= 640, 2 images.(left above 3 images, do the rest 7 images ORDER BY RAND())

所有5张图片都没有重复.我的思绪现在很困惑,需要帮助.

ain*_*ain 5

好吧,如果我正确地理解你的问题你想要做的事情

(SELECT image FROM tab WHERE(first) ORDER BY RAND() LIMIT 1)
UNION
(SELECT image FROM tab WHERE(second) ORDER BY RAND() LIMIT 2)
UNION
(SELECT image FROM tab WHERE(third) ORDER BY RAND() LIMIT 2)
Run Code Online (Sandbox Code Playgroud)

在每个WHERE子句中替换first,secondthird使用正确的约束...