select ... where(a = 1或b = min(b))GROUP BY xy

时间:2013-01-11 17:12:13

标签: mysql

我有表gall_photos,其中包含许多画廊的照片

  • id(int)
  • gall_id(int)
  • filename(varchar)
  • position(int)
  • 预览(tinyint 1)
  • date_add(datetime)

现在我想获得照片列表(用于摘要预览),每个gall_id中的一个,但如果有预览1,那么这个,其他照片的位置编号最低。最后按date_add

排序
select * 
from gall_photos 
where (preview = 1 or position = min(position)) 
group by gall_id 
order by date_add

此查询返回错误(如果使用“或position = min(position)”)

请知道吗?

编辑(12.1.18:50UTC):可以在一个图库(gall_id)中检查更多照片的预览,然后我需要其中一个,再次是最低位置

5 个答案:

答案 0 :(得分:1)

你可以这样做

select * 
from gall_photos x 
where (preview = 1 or (position = 
                             (SELECT min(x2.position)
                              FROM gall_photos x2 
                              WHERE x.gall_id = x2.gall_id
                              Group By x2.gall_id)
                      and not exists 
                              (select 1 
                               from gall_photos x2 
                               where x2.gall_id=x.gall_id 
                               and x2.preview=1)
                        )
       );

SQL FIDDLE DEMO

答案 1 :(得分:0)

select id, gall_id, filename, position, preview, date_add
from gall_photos 
where position in (select min(position)from gall_photos) 
or
exists (select preview from gall_photos where preview = 1)
group by gall_id
order by date_add;

答案 2 :(得分:0)

rs的解决方案非常接近,但是如果你有一个记录,其中preview = 1并且它没有gall_id的最低位置,那么他将给你预览= 1和最低位置。所以我认为你想要的是:

select * 
from gall_photos g1
where preview = 1
  or not exists (select * from gall_photos g2 where g2.gall_id=g1.gall_id and g2.preview=1)
  and position = (select min(g3.position) from gall_photos g3
    where g3.gall_id=g1.gall_id)
order by date_add

答案 3 :(得分:0)

这样的事情怎么样......

SELECT a.gall_id
     , COALESCE(c.position,a.position) position
  FROM gall_photos a
  JOIN 
     ( SELECT gall_id,MIN(position) min_position FROM gall_photos GROUP BY gall_id) b 
    ON b.gall_id = a.gall_id 
   AND b.min_position = a.position
  LEFT
  JOIN gall_photos c
    ON c.gall_id = a.gall_id
   AND c.preview = 1;

答案 4 :(得分:0)

WHERE CLAUSE

不允许

GROUP BY

使用HAVING

select * 
from gall_photos 
group by gall_id 
having (preview = 1 or position = min(position)) 
order by date_add