使用where子句选择X,使用where子句选择Y.

时间:2016-02-17 08:48:32

标签: mysql

我试图弄清楚是否可以进行如下查询:

Select 5 from pictures where likes < 5 && select 4 from pictures

基本上,在前5张图片上有一个where子句,并获得4张图片(但要确保这些其他4张图片与前5张图片不同)..

这是我到目前为止所做的:

SELECT * FROM `pictures` WHERE `likes` < 5 GROUP BY id desc limit 0,5;

这是我希望得到的结果:

Picture 1 (Using where clause)
Picture 2 (Using where clause)
Picture 3 (Using where clause)
Picture 4 (Using where clause)
Picture 5 (Using where clause)
Picture 6 (Randomly selected from pictures, but making sure that this isn't a duplicate)
Picture 7 (Randomly selected from pictures, but making sure that this isn't a duplicate)
Picture 8 (Randomly selected from pictures, but making sure that this isn't a duplicate)
Picture 9 (Randomly selected from pictures, but making sure that this isn't a duplicate)

基本上,每当我查询它时,我都希望所有行都是唯一的。

2 个答案:

答案 0 :(得分:0)

这样的事情:

Select * from pictures where likes < 5 limit 0,5

union all

Select * from pictures where likes >= 5 order by rand() limit 0,4

答案 1 :(得分:0)

你可以使用union:

SELECT * FROM `pictures` WHERE `likes` < 5 group by id order by id desc limit 0,5
UNION ALL
(SELECT * FROM `pictures`
WHERE id not in(SELECT id FROM `pictures` WHERE `likes` < 5 group by id order by id desc limit 0,5)
limit 0,4)

这样你就可以选择带有where子句的5张图片,另外4张带有where的图片(仅过滤那些已被选中的图片)